答案 0 :(得分:4)
创建所需大小的BufferedImage,例如:
BufferedImage img = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB)
用适当的背景颜色填充它:
img.getGraphics().fillRect(....)
在该背景顶部的图像图形上调用drawImage:
img.getGraphics().drawImage(image, 0, 0, null);
然后像往常一样将图像写为JPG。
答案 1 :(得分:4)
您使用的是哪种颜色模式?在创建缓冲图像对象时,请尝试添加类似此选项的类型。
File newFile = new File(path + fileName + "." + Strings.FILE_TYPE);
Image image = null;
try {
image = ImageIO.read(url); // I was using an image from web
} catch (IOException e1) {
e1.printStackTrace();
}
image = image.getScaledInstance(width, height, Image.SCALE_SMOOTH);
try {
BufferedImage img = toBufferedImage(image);
ImageIO.write(img, "jpg", newFile);
} catch (IOException e) {
e.printStackTrace();
}
}
private static BufferedImage toBufferedImage(Image src) {
int w = src.getWidth(null);
int h = src.getHeight(null);
int type = BufferedImage.TYPE_INT_RGB; // other options
BufferedImage dest = new BufferedImage(w, h, type);
Graphics2D g2 = dest.createGraphics();
g2.drawImage(src, 0, 0, null);
g2.dispose();
return dest;
}