在Java中将PNG字节数组转换为JPEG字节数组 [英] Converting PNG byte array to JPEG byte array in java

查看:156
本文介绍了在Java中将PNG字节数组转换为JPEG字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定我在这里到底在做什么,所以请提供一些建议并原谅错误.

I am not sure what I am exactly doing here so please give some advise and forgive the mistakes.

我有一个名为idCardImage的图像byte[],我执行了以下操作将其转换为字符串:

I have a image byte[] called idCardImage and I did the following to convert it to a String:

String s = new String(idCardImage);

它像这样打印出来:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAEHUlEQVQ4TzWUW49VRRCFv6rq3ufMmTNn....

进行了一些在线搜索,该图像似乎是png格式,且以base 64编码.

Did some search online and it seems this image is in a png format with base 64 encoded.

我需要做的是将其转换为jpeg格式,然后将其存储在新的字节数组中.您可以提供一些有关如何使用Java的建议吗?

What I need to do is to convert it to a jpeg format and then store it in a new byte array. Can you give some advise on how to do it with Java?

推荐答案

我不确定这是否是最有效的方法,但是您可以:

I am not sure if that is most efficient way, but you could:

1)将数据从该字符串转换为表示图像的字节,例如:

1) convert data from that string to bytes representing image, like:

String dataUrl = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAEHUlEQVQ4TzWUW49VRRCFv6rq3ufMmTNn...";
String header = "data:image/png;base64";

String encodedImage = dataUrl.substring(header.length()+1); //+1 to include comma 
byte[] imageData = Base64.getDecoder().decode(encodedImage); //decode bytes

2)将这些字节转换为保存PNG图像的BufferedImage

2) convert that bytes to BufferedImage holding PNG image

BufferedImage bufferedImage = ImageIO.read(new ByteArrayInputStream(imageData));

3),然后基于 http ://www.mkyong.com/java/convert-png-to-jpeg-image-file-in-java/中,您可以创建单独的BufferedImage并使用

3) then based on http://www.mkyong.com/java/convert-png-to-jpeg-image-file-in-java/ you could create separate BufferedImage and fill it using JPG fromat

 // create a blank, RGB, same width and height, and a white background
 BufferedImage newBufferedImage = new BufferedImage(bufferedImage.getWidth(),
        bufferedImage.getHeight(), BufferedImage.TYPE_INT_RGB);
 newBufferedImage.createGraphics().drawImage(bufferedImage, 0, 0, Color.WHITE, null);

(可以使用ImageIO.write(source, format, output)简化此步骤,如 @Channa Jayamuni答案 )

(this step can be simplified with ImageIO.write(source, format, output) as shown in @Channa Jayamuni answer)

4)最后,我们几乎不需要ByteArrayOutputStream就能将这些字节写到单独的字节数组中

4) finally we can write these bytes to separate byte array with little help of ByteArrayOutputStream

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

这篇关于在Java中将PNG字节数组转换为JPEG字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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