【问题标题】:How to convert ImageIcon to File object wihout saving it into disk?如何将 ImageIcon 转换为 File 对象而不将其保存到磁盘中?
【发布时间】:2014-08-24 13:27:04
【问题描述】:

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

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

【问题讨论】:

  • 否;你需要另一种InputStream
  • 您最初是如何创建 ImageIcon 的?我的猜测是您是从 InputStream 创建的。那么为什么不将这个 InputStream 传递给 setBinaryStream() 呢?
  • Blob blob = rset.getBlob(5);字节日期[] = blob.getBytes(1, (int)blob.length());图片.add(new ImageIcon(date));
  • 另存为Blob而不是File

标签: java swing file jdbc imageicon


【解决方案1】:

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

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;
}

【讨论】:

  • 我在 cast:java.lang.ClassCastException 遇到异常:sun.awt.image.ToolkitImage 无法转换为 java.awt.image.BufferedImage
猜你喜欢
  • 2014-11-08
  • 2021-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-09
  • 1970-01-01
  • 1970-01-01
  • 2017-10-21
相关资源
最近更新 更多