在Java中调整MultipartFile大小后,图像变黑了。
我正在尝试在sql db中保存文件..由于内存的原因,我需要降低图像的质量和尺寸。调整大小后它会变黑...
任何想法?
private static int IMG_HEIGHT = 1280;
private static int IMG_WIDTH= 860;
private static int imgType = Image.SCALE_SMOOTH;
try {
byteArr = doc.getBytes();
ImageIcon imgIcon = new ImageIcon(byteArr);
int height = imgIcon.getIconHeight();
int width = imgIcon.getIconWidth();
if(height > IMG_HEIGHT || width > IMG_WIDTH){
int newWidth = width;
int newHeight = height;
if(height > IMG_HEIGHT){
newHeight = IMG_HEIGHT;
}
if(width > IMG_WIDTH){
newWidth = IMG_WIDTH;
}
System.out.println("Img newHeight = "+newHeight);
System.out.println("Img newWidth = "+newWidth);
Image newImage = imgIcon.getImage();
newImage = newImage.getScaledInstance(newWidth, newHeight, imgType);
BufferedImage buffImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = buffImage.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2.drawImage(newImage, 0, 0, width, height, null);
// g2.setColor(Color.WHITE);
// g2.fillRect(0, 0, newWidth, newHeight);
// g2.setComposite(AlphaComposite.SrcOver);
// AffineTransform scaleTransform = AffineTransform.getScaleInstance(width / (double) newImage.getWidth(null), height / (double) newImage.getHeight(null));
// g2.drawImage(newImage, scaleTransform, null);
g2.dispose();
baos = new ByteArrayOutputStream();
ImageIO.write(buffImage,"jpg", baos);
答案 0 :(得分:0)
我对具有透明背景的图像有类似的问题。
只需将Color.WHITE
中的graphics.drawImage
作为背景颜色传递,即可避免黑色背景。
Graphics2D graphics = buffImage.createGraphics();
graphics.drawImage(newImage, 0, 0, IMAGE_WIDTH, IMAGE_HEIGHT, Color.WHITE, null);
graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.DST_IN, 1.0f));
答案 1 :(得分:-1)
我使用了Scalr库,它只在一行中解决了我的主题:)
BufferedImage thumbS = Scalr.resize(bImageFromConvert, Scalr.Method.BALANCED, IMG_HEIGHT, IMG_WIDTH, Scalr.OP_ANTIALIAS);
其中bImageFromConvert是BufferedImage ...