如何将ImageIcon转换为File对象而不将其保存到磁盘?

时间:2014-08-24 13:27:04

标签: java swing file jdbc imageicon

我想使用jdbc将ImageIcon发送到数据库。 我需要File对象来做到这一点。 如何将ImageIcon转换为File而不将其保存到磁盘中?

File fBlob = new File(imageIcon.getImage());
FileInputStream is = new FileInputStream ( fBlob );
preparedStatement.setBinaryStream (3, is, (int) fBlob.length() );

1 个答案:

答案 0 :(得分:1)

可能您可以尝试从byte array获取imageIcon,然后将其写入数据库。像这样:

BufferedImage bi = getBufferedImage(imageIcon.getImage());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bi, formatType, baos);

byte[] byteArray= baos.toByteArray();

preparedStatement.setBytes(1, byteArray);

编辑:

使用此方法将Image转换为BufferedImage

public static BufferedImage getBufferedImage(Image img)
{
    if (img instanceof BufferedImage)
    {
       return (BufferedImage) img;
    }

    BufferedImage bimage = new BufferedImage(img.getWidth(null), 
                    img.getHeight(null), BufferedImage.TYPE_INT_ARGB);

    Graphics2D bGr = bimage.createGraphics();
    bGr.drawImage(img, 0, 0, null);
    bGr.dispose();

    // Return the buffered image
    return bimage;
}