我有一种方法可以使用filechooser加载图像,然后将图像调整为指定大小以将其存储在DB中。我使用com.sun.image.codec.jpeg.JPEGCodec和JPEGImageEncoder,我需要将其更改为ImageIO,因为我无法在netbeans 7.4 IDE上使用它。这就是我所拥有的。
FileInputStream fis = new FileInputStream(image);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
for (int readNum; (readNum = fis.read(buf)) != -1; ) {
bos.write(buf, 0, readNum);
}
person_image = bos.toByteArray();
ImageIcon imageIcon = new ImageIcon(person_image);
Image img = imageIcon.getImage();
Image imageResize = img.getScaledInstance(lbl_fotoPaciente.getWidth(), lbl_fotoPaciente.getHeight(), Image.SCALE_SMOOTH);
ImageIcon imageIconResize = new ImageIcon(imageResize);
int resizeWidth = imageIconResize.getIconWidth();
int resizeHeight = imageIconResize.getIconHeight();
Panel p = new Panel();
BufferedImage bi = new BufferedImage(resizeWidth, resizeHeight,
BufferedImage.TYPE_INT_RGB);
Graphics2D big = bi.createGraphics();
big.drawImage(imageResize, 0, 0, p);
ByteArrayOutputStream os = new ByteArrayOutputStream();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
encoder.encode(bi);
person_image = os.toByteArray();
lbl_fotoPaciente.setIcon(new ImageIcon(imageResize));
如何将其更改为ImageIO?感谢。
答案 0 :(得分:3)
您只需将最后一行替换为:
...
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(bi, "JPEG", os);
person_image = os.toByteArray();
...