JAVA迅速解决图片变红、变黑、压缩平滑问题

小卒 最近在做头像上传功能,发现对于带有alpha通道的图片,有的会变红,有的会变黑,有时压缩不平滑。发现是有几处程序写错了。

首先贴一下原始的程序,这段程序的功能是将原图的(x,y,w,h)图块,转变为 (0,0,targetW,targetH)图片,并输出为jpg格式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

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
}
}

首先是背景有时变黑,这里最简单的做法是将最后的背景图片设置为白色。见下面代码:

1
2
3

//graph.drawImage(cropedImage, 0, 0, targetW, targetH, null);
graph.drawImage(cropedImage, 0, 0, targetW, targetH, Color.white,null);

加一个Color.white即可。

下面要解决的是图片变红问题。 帐前卒 认为这个问题其实是alpha通道需要变为透明的。而原始程序是判断,如果
该图片是定义为Custom的图片,那么就变为透明。显然custom的图片不一定是透明图片。所以这里需要判断image是否为透明的。代码变为:

1
2
3
4
5
6
7
8
9
10

// 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);
}

然后变红问题就解决了。下面是压缩图片时,发现很多地方不光滑,这里也非常好解决。帐 前卒的代码如下: ```

// 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);

加入SCALE_SMOOTH参数就完成了~~