Java – use imageio Write() creates a JPEG file of 0 bytes

I'm trying to write a way to take an image and save a 100 x 100 thumbnail of the image However, when I save the file, it is an unreadable 0-byte image (error interpretation "error interpretation JPEG image file (error call to JPEG Library in state 200)") in Ubuntu's ImageViewer My code is as follows:

public boolean scale(){

    String file = filename.substring(filename.lastIndexOf(File.separator)+1);
    File out = new File("data"+File.separator+"thumbnails"+File.separator+file);

    if( out.exists() ) return false;

    BufferedImage bi;
    try{
        bi = ImageIO.read(new File(filename));
    }
    catch(IOException e){
        return false;
    }

    Dimension imgSize = new Dimension(bi.getWidth(),bi.getHeight());
    Dimension bounds = new Dimension(100,100);
    int newHeight = imgSize.height;
    int newWidth = imgSize.width;

    if( imgSize.width > bounds.width ){
        newWidth = bounds.width;
        newHeight = (newWidth*imgSize.height)/imgSize.width;
    }

    if( imgSize.height > bounds.width ){
        newHeight = bounds.height;
        newWidth = (newHeight*imgSize.width)/imgSize.height;
    }

    Image img = bi.getScaledInstance(newWidth,newHeight,BufferedImage.SCALE_SMOOTH);
    BufferedImage thumb = new BufferedImage(newWidth,BufferedImage.TYPE_4BYTE_ABGR);
    Graphics2D g2d = thumb.createGraphics();
    g2d.drawImage(img,null);
    g2d.dispose();

    try{
        ImageIO.write(thumb,"jpg",out);
    }
    catch(IOException e){
        return false;
    }

    return true;
}

Where "filename" is the global variable of the class containing this method, representing the path of the original image My main problem is that I don't understand why I want to create a 0 - byte image

Solution

So the problem is this I work in openjdk Obviously, openjdk does not have a JPEG encoder, so when creating files

ImageIO.write(thumb,out);

It doesn't actually create anything for the file to be saved; Therefore, an empty 0 byte unreadable file Changing the imageio parameter to "PNG" (and adjusting the new file () extension accordingly) has successfully created the required image using the above code

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>