Java生成图片红色问题
Java上传图片时,对某些图片进行缩放、裁剪或者生成缩略图时会蒙上一层红色, 经过检查只要经过ImageIO.read()方法读取后再保存,该图片便已经变成红图。 因此,可以推测直接原因在于ImageIO.read()方法加载图片的过程存在问题。
1、解决 :而使用JDK中提供的Image
如果是file
Image src=Toolkit.getDefaultToolkit().getImage(file.getPath());
如果是url
URL url = new URL(wechat_erweimaTmail);
java.awt.Image imageTookittitle = Toolkit.getDefaultToolkit().createImage(url);
BufferedImage titleLab = ImageUtils.toBufferedImage(imageTookittitle);
public static BufferedImage toBufferedImage(Image image) {
if (image instanceof BufferedImage) {
return (BufferedImage) image;
}
// This code ensures that all the pixels in the image are loaded
image = new ImageIcon(image).getImage();
BufferedImage bimage = null;
GraphicsEnvironment ge = GraphicsEnvironment
.getLocalGraphicsEnvironment();
try {
int transparency = Transparency.OPAQUE;
GraphicsDevice gs = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gs.getDefaultConfiguration();
bimage = gc.createCompatibleImage(image.getWidth(null),
image.getHeight(null), transparency);
} catch (HeadlessException e) {
// The system does not have a screen
}
if (bimage == null) {
// Create a buffered image using the default color model
int type = BufferedImage.TYPE_INT_RGB;
bimage = new BufferedImage(image.getWidth(null),
image.getHeight(null), type);
}
// Copy image to buffered image
Graphics g = bimage.createGraphics();
// Paint the image onto the buffered image
g.drawImage(image, 0, 0, null);
g.dispose();
return bimage;
}
感兴趣的,欢迎添加博主微信,
哈,博主很乐意和各路好友交流,如果满意,请打赏博主任意金额,感兴趣的在微信转账的时候,备注您的微信或者其他联系方式。添加博主微信哦。
请下方留言吧。可与博主自由讨论哦
支付包 | 微信 | 微信公众号 |
---|---|---|
![]() |
![]() |
![]() |