【问题标题】:converting Image in memory to a Blob [closed]将内存中的图像转换为 Blob [关闭]
【发布时间】:2014-01-06 23:14:22
【问题描述】:

我在内存中有一个图像(类型:java.awt.Image),我想使用 jdk 1.7 将其转换为 Blob(类型:java.sql.Blob)。

我在这个主题上找到的所有内容都使用流和文件。当然我不需要在转换之前将此图像保存到文件中??

这里不多展示,下面是一个例子:

导入 java.sql.Blob; 导入 java.awt.Image;

public GenericResponseType savePhoto(Image image)
{
       Connection conn = ds.getConnection();

       << some DB code and assembly of PreparedStatement >>

       Blob blob = conn.createBlob();

           << here's where the magic needs to happen I need to get the image parameter to blob >>
           // I've tried the following but doesn't quite work as it wants a RenderedImage
       // OutputStream os = blob.setBinaryStream(1);
       // ImageIO.write(parameters.getPhoto().getImage(), "jpg", os);


       pstmt.setBlob(4, blob);
     }

更多细节(尽管我怀疑它很重要)是上面的内容是使用来自 WSDL 的 Web 服务/JAX-WS 生成的,并且使用 MTOM 声明了一个操作。所以它会生成一个签名,其中一个 Image 作为变量传递。

【问题讨论】:

  • 否,但您需要先将其放入 BufferedImage

标签: java image oracle jax-ws


【解决方案1】:

java.awt.Image 非常简单。它不提供任何可以写入/保存图像的方法,也不提供任何访问图像底层像素数据的方法。

第一步,将java.awt.Image 转换为ImageIO 可以支持的东西。这将允许您将图像数据写出...

ImageIO 需要 RenderedImage 作为主要图像源。 BufferedImage 是该接口在默认库中的唯一实现...

不幸的是,没有一种简单的方法可以从一种转换为另一种。幸运的是,这并不难。

Image img = ...;

BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = bi.createGraphics();
g2d.drawImage(img, 0, 0, null);
g2d.dispose();

基本上,这只是将原始的java.awt.Image 绘制到BufferedImage

接下来,我们需要以某种方式保存图像,以便它可以生成InputStream...

这不是最理想的,但可以完成工作。

ByteArrayOutputStream baos = null;
try {
    baos = new ByteArrayOutputStream();
    ImageIO.write(bi, "png", baos);
} finally {
    try {
        baos.close();
    } catch (Exception e) {
    }
}
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());

基本上,我们将图像写入ByteArrayOutputStream,然后使用结果生成ByteArrayInputStream

现在。如果内存有问题或图像相当大,您可以先将图像写入File,然后通过某种InputStreamFile 读回...

最后,我们将InputStream 设置为所需的列...

PreparedStatement stmt = null;
//...    
stmt.setBlob(parameterIndex, bais);

Blob 是你的叔叔……

【讨论】:

  • 非常感谢。我已经将上述方法视为一种可能的方法,但对于表面上看起来应该非常简单的事情来说似乎工作量太大了。我可能只需要使用文件 IO。
【解决方案2】:

尝试以下方法:(可能是一个更简单的过程,这只是我在快速搜索后发现的,不能保证它会起作用 - Mads 的答案看起来更可信)。

  1. 获取 BufferedImage (From this answer)

    BufferedImage buffered = new BufferedImage(scaleX, scaleY, TYPE);
    buffered.getGraphics().drawImage(image, 0, 0 , null);
    
  2. 获取一个字节数组(From this answer

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(buffered, "jpg", baos );
    byte[] imageInByte = baos.toByteArray();
    
  3. 将字节数组保存为 blob (From this answer)(但可能应该使用 Prepared Statement)

    Blob blob = connection.createBlob();
    blob.setBytes(1, imageInByte);
    

【讨论】:

    猜你喜欢
    • 2012-11-04
    • 2013-02-15
    • 2016-05-29
    • 1970-01-01
    • 2020-09-23
    • 2013-07-01
    • 2015-10-16
    • 2017-07-11
    • 2015-05-05
    相关资源
    最近更新 更多