Java将图像转换为输入流而不创建文件 [英] Java converting an image to an input stream WITHOUT creating a file

查看:581
本文介绍了Java将图像转换为输入流而不创建文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我正在处理的applet,我需要将 BufferedImage 文件转换为输入流,以便我可以将图像上传到我的MySQL服务器。最初我使用的是这段代码:

For an applet I'm working on I need to convert a BufferedImage file to an input stream so that I can upload the image to my MySQL server. Originally I was using this code:

Class.forName("com.mysql.jdbc.Driver").newInstance();  
Connection connection = 
    DriverManager.getConnection(connectionURL, "user", "pass");  

psmnt = connection.prepareStatement(
    "insert into save_image(user, image) values(?,?)");  
psmnt.setString(1, username);  

ImageIO.write(image, "png", new File("C://image.png")); 
File imageFile = new File("C://image.png");
FileInputStream fis = new FileInputStream(imageFile);

psmnt.setBinaryStream(2, (InputStream)fis, (fis.length()));
int s = psmnt.executeUpdate();

if(s > 0) {
  System.out.println("done");
}

(同时捕获相关的例外)代码挂在applet的部分尝试将图像保存到计算机。代码在Eclipse中完美运行,或者每当我从localhost运行applet时,我都认为问题在于applet将文件保存到用户计算机的权限。

(while catching the relevant exceptions) The code hangs on the part where the applet attempts to save the image to the computer. The code worked perfectly in Eclipse or whenever I ran the applet from the localhost, so I'm assuming the problem is in the privileges that the applet has in saving files to the user's computer.

我只是想知道是否有办法将图像文件转换为输入流而无需将文件保存到用户的计算机。我尝试使用:

I was just was wondering if there was a way to turn the image file into an inputstream without having to save a file to the user's computer. I tried using:

ImageIO.createImageInputStream(image);

然后我无法转换 ImageInputStream 返回 InputStream 。任何建议?

But then I couldn't convert the ImageInputStream back to an InputStream. Any Suggestions?

谢谢!

推荐答案

通常你会使用一个用于此目的的ByteArrayOutputStream。它充当内存中的流。

Typically you would use a ByteArrayOutputStream for that purpose. It acts as an in-memory stream.

ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(image,"png", os); 
InputStream fis = new ByteArrayInputStream(os.toByteArray());

这篇关于Java将图像转换为输入流而不创建文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆