Pawn was recently working on the Avatar upload function, and found that some images with alpha channels will become red, some will become black, and sometimes the compression is not smooth. I found several program errors.
First, paste the original program. The function of this program is to convert the graph blocks (x, y, w, h) of the source image to (, targetW, targetH) images, and the output is in jpg format.
private byte[] cropAndCompressImage(int x, int y, int w, int h, BufferedImage image, int targetW, int targetH) throws Exception{ if (w == -1 && h == -1 && image != null) { // use full image w = image.getWidth(); h = image.getHeight(); } if (x < 0 || y < 0 || w <= 0 || h <= 0 || image == null) { // error } w = Math.min(x+w, image.getWidth()) - x; h = Math.min(y+h, image.getHeight()) - y; try { BufferedImage cropedImage = image.getSubimage(x, y, w, h); // do image compression int type = image.getType() == 0 ? BufferedImage.TRANSLUCENT : image.getType(); BufferedImage compressedImage = new BufferedImage(targetW, targetH, type); Graphics2D graph = compressedImage.createGraphics(); graph.drawImage(cropedImage, 0, 0, targetW, targetH, null); graph.dispose(); ByteArrayOutputStream bytes = new ByteArrayOutputStream(); ImageIO.write(compressedImage, "jpg", bytes); return bytes.toByteArray(); } catch (IOException e) { // error } }
First, the background turns black. The simplest method here is to set the final background image to white. See the following code:
//graph.drawImage(cropedImage, 0, 0, targetW, targetH, null); graph.drawImage(cropedImage, 0, 0, targetW, targetH, Color.white,null);
Add Color. white.
What we need to solve below is the problem of red images. Before accounting, I think this problem is actually caused by the need to make the alpha channel transparent. The original program determines that if the image is a Custom image, it becomes transparent. Obviously, custom images are not necessarily transparent images. Therefore, you need to determine whether the image is transparent. Code changed:
// int type = image.getType() == 0 ? BufferedImage.TRANSLUCENT : image.getType(); // BufferedImage compressedImage = new BufferedImage(targetW, targetH, type); BufferedImage compressedImage = null; if (image.isAlphaPremultiplied()) { compressedImage = new BufferedImage(photoType.getWidth(), photoType.getHeight(), BufferedImage.TRANSLUCENT); } else { compressedImage = new BufferedImage(photoType.getWidth(), photoType.getHeight(), BufferedImage.TYPE_INT_RGB); }
Then the problem is solved. The following figure shows that the image is not smooth in many places, which is also a good solution. The code of the account is as follows:
// graph.drawImage(cropedImage, 0, 0, targetW, targetH, null); // graph.drawImage(cropedImage, 0, 0, targetW, targetH, Color.white,null); graph.drawImage(cropedImage.getScaledInstance(targetW, targetH, BufferedImage.SCALE_SMOOTH), 0, 0, Color.white,null);
The SCALE_SMOOTH parameter is added ~~