Java从inputStream创建图像
我正在从inputStream创建图像,我使用了两种方法,但两种方法都失败了 第一种方法:Java从inputStream创建图像,java,image,grails,javax.imageio,Java,Image,Grails,Javax.imageio,我正在从inputStream创建图像,我使用了两种方法,但两种方法都失败了 第一种方法: FileOutputStream out=new FileOutputStream(file) byte[] byteBuffer = new byte[1024]; int length = 0; while ((stream != null) && ((length = stream.read(byteBuffer)) != -1)){ out.write(byteBuffer,0,l
FileOutputStream out=new FileOutputStream(file)
byte[] byteBuffer = new byte[1024];
int length = 0;
while ((stream != null) && ((length = stream.read(byteBuffer)) != -1)){
out.write(byteBuffer,0,length);
}
out.flush()
out.close();
stream.close();
此方法在尝试打开图像时生成图像。它显示“这不是有效的位图文件”
第二种方法是:
BufferedImage imBuff = ImageIO.read(stream);
ImageIO.write(imBuff, 'png', file);
这一个生成了异常
java.lang.IllegalArgumentException:image==null!
在javax.imageio.ImageTypeSpecifier.CreateFromRenderImage(ImageTypeSpe
cifier.java:925)
位于javax.imageio.imageio.getWriter(imageio.java:1591)
在javax.imageio.imageio.write(imageio.java:1520)
在com.k12report.frontend.ClientAuthoringController$$EOU2Lt2o.getImages上(
ClientAuthoringController.groovy:55)
在grails.plugin.cache.web.filter.PageFragmentCachingFilter.doFilter(Pag
eFragmentCachingFilter.java:195)
位于grails.plugin.cache.web.filter.AbstractFilter.doFilter(AbstractFilter
.java:63)
位于java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor。
爪哇:1145)
位于java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor
.java:615)
运行(Thread.java:722)
谢谢,这不是一个有效的位图文件 如果您使用的是依赖于操作系统的文件路径,则更推荐使用File.separator,而不是使用“\”或“/”。它们使您的代码更易于移植 示例:-
File f=新文件(“C:+File.separator+“Personal”+File.separator+“test.bmp”)代码>什么是流
?它的内容是什么?您是否尝试过将内容转储到磁盘并通过外部映像程序验证其有效性?stream=response.getEntityInputStream()是否确实有一个有效的映像开始?在第二种方法中,imBuff
为null
,当ImageIO无法识别文件格式时会发生这种情况。你需要测试一下这种情况。我觉得你的第一种方法不错。您可能应该检查流!=空
在可读性和性能的循环之外。谁说:这不是有效的位图文件?(我不清楚……)我使用的是grails,所以,def root=getServletContext().getRealPath(“”);字符串路径=根+'/authoringImages/'+图像文件=新文件(路径)代码>对我来说,使用/作为文件分隔符总是有效的(在使用文件对象时)…在使用windows时也是如此。。。。