0

Image turns black after resizing MultipartFile in Java ..

I am trying to save file in sql db.. I need to down image quality and size because of memory..after resizing it gets black ..

any ideas?

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);
user3414260
  • 257
  • 2
  • 6

2 Answers2

0

I had a similar issue with images with transparent background. Just passing Color.WHITE in graphics.drawImage as a background color helped to avoid black background.

    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));
Sergii Bishyr
  • 8,331
  • 6
  • 40
  • 69
-1

I used Scalr library and it solved my subject just in one line :)

BufferedImage thumbS = Scalr.resize(bImageFromConvert, Scalr.Method.BALANCED, IMG_HEIGHT, IMG_WIDTH, Scalr.OP_ANTIALIAS);  

where bImageFromConvert is BufferedImage...

user3414260
  • 257
  • 2
  • 6