我正在尝试编写一个拍摄图像的方法,并保存该图像的100 x 100缩略图.但是,当我保存文件时,它是一个不可读的0字节图像(错误解释“错误解释JPEG图像文件(在状态200中对JPEG库的错误调用)”)在Ubuntu的
ImageViewer中.我的代码如下:
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; }
其中“filename”是容纳此方法的类的全局变量,表示原始图像的路径.我的主要问题是我不明白为什么我要创建一个0字节的图像.