java的image数组_Java:BufferedImage到字节数组并返回

Java:BufferedImage到字节数组并返回

我看到一些人有类似的问题,但我还没有find我正在寻找的东西。

所以,我有一个方法读取input图像,并将其转换为字节数组:

File imgPath = new File(ImageName); BufferedImage bufferedImage = ImageIO.read(imgPath); WritableRaster raster = bufferedImage .getRaster(); DataBufferByte data = (DataBufferByte) raster.getDataBuffer();

我现在想要做的是将其转换回BufferedImage(我有一个应用程序,我需要这个function)。 请注意,“testing”是字节数组。

BufferedImage img = ImageIO.read(new ByteArrayInputStream(test)); File outputfile = new File("src/image.jpg"); ImageIO.write(img,"jpg",outputfile);

但是,这会返回以下exception:

Exception in thread "main" java.lang.IllegalArgumentException: im == null!

这是因为BufferedImage img为空。 我认为这与事实有关,在从BufferedImage到字节数组的原始转换中,信息被改变/丢失,使得数据不能再被识别为jpg。

有没有人有任何build议如何解决这个问题? 将不胜感激。

build议将其转换为字节数组

ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(img, "jpg", baos); byte[] bytes = baos.toByteArray();

请注意,调用close或flush将什么也不做,你可以通过查看他们的source / doc来看到这个:

closures一个ByteArrayOutputStream没有效果。

OutputStream的flush方法什么都不做。

因此使用这样的东西:

ByteArrayOutputStream baos = new ByteArrayOutputStream(THINK_ABOUT_SIZE_HINT); boolean foundWriter = ImageIO.write(bufferedImage, "jpg", baos); assert foundWriter; // Not sure about this... with jpg it may work but other formats ? byte[] bytes = baos.toByteArray();

以下是关于尺寸提示的几个链接:

Java:内存高效的ByteArrayOutputStream

每像素jpg位

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值