使用ImageIO.write()创建JPEG会创建一个0字节的文件

Tho*_*ton 7 java byte jpeg zero javax.imageio

我正在尝试编写一个拍摄图像的方法,并保存该图像的100 x 100缩略图.然而,当我保存文件时,它出来作为一个不可读0字节的图像(与错误"错误地解释了JPEG图像文件(不正确的呼叫状态200 JPEG库)")在Ubuntu的图像浏览器.我的代码如下:

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, newHeight, BufferedImage.TYPE_4BYTE_ABGR);
    Graphics2D g2d = thumb.createGraphics();
    g2d.drawImage(img, 0, 0, null);
    g2d.dispose();

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

    return true;
}
Run Code Online (Sandbox Code Playgroud)

其中"filename"是容纳此方法的类的全局变量,表示原始图像的路径.我的主要问题是我不明白为什么我要创建一个0字节的图像.

Tho*_*ton 5

所以,问题是这样的。我在OpenJDK中工作。显然,OpenJDK没有JPEG编码器,因此当文件由

ImageIO.write(thumb, "jpg", out);
Run Code Online (Sandbox Code Playgroud)

实际上并没有创建任何要保存的文件;因此为空的0字节不可读文件。使用上述代码,将ImageIO参数更改为“ png”(并适当地调整新的File()扩展名)可以成功创建所需的图像。