Java 将内存中的图像转换为Blob

Java 将内存中的图像转换为Blob,java,image,oracle,jax-ws,Java,Image,Oracle,Jax Ws,我在内存中有一个映像(类型:java.awt.Image),我想使用JDK1.7将其转换为Blob(类型:java.sql.Blob) 我能找到的关于这个主题的所有东西都使用流和文件。当然,我不需要将此图像保存到文件中,然后才能将其转换 这里没有太多说明,但下面是一个示例: 导入java.sql.Blob; 导入java.awt.Image public GenericResponseType savePhoto(Image image) { Connection conn = d

我在内存中有一个映像(类型:java.awt.Image),我想使用JDK1.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);
     }
publicGenericResponseType保存照片(图像)
{
连接conn=ds.getConnection();
>
Blob Blob=conn.createBlob();

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

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

ImageIO
需要一个
RenderImage
作为其主要映像源。
BuffereImage
是默认库中此接口的唯一实现

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

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

现在。如果内存有问题或图像太大,您可以先将图像写入
文件
,然后通过某种
输入流
文件
读回

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

PreparedStatement stmt = null;
//...    
stmt.setBlob(parameterIndex, bais);
Blob是你的叔叔……

试试下面的方法:(可能是一个简单得多的过程,这正是我在快速浏览后发现的,不能保证它会起作用——Mads的答案看起来更可信)

  • 获取一个BuffereImage()

  • 获取字节数组()

  • 将字节数组另存为blob()(但可能会使用一个准备好的语句)


  • 不,但您需要先将其放入BuffereImage。非常感谢。我已经将上述方法视为一种可能的方法,但对于表面上看起来应该非常简单的东西来说,似乎太多的工作了。我可能不得不使用文件IO。
    BufferedImage buffered = new BufferedImage(scaleX, scaleY, TYPE);
    buffered.getGraphics().drawImage(image, 0, 0 , null);
    
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(buffered, "jpg", baos );
    byte[] imageInByte = baos.toByteArray();
    
    Blob blob = connection.createBlob();
    blob.setBytes(1, imageInByte);