HarmonyOS 通过RawFileEntry读取PNG图片PixelMap,经ImagePacker编码,为JPEG格式。

HarmonyOS 通过RawFileEntry读取PNG图片PixelMap,经ImagePacker编码,为JPEG格式。本来PNG图片是透明图片,转成JPEG格式后成黑色背景。代码如下:如何不产生黑色背景。

 

RawFileEntry rawFileEntry = getContext().getResourceManager().getRawFileEntry("resources/rawfile/ccdraw/assets/symbol_PLA/commandorgan/6.png");
Resource resource = rawFileEntry.openRawFile();
ImageSource.SourceOptions sourceOptions = new ImageSource.SourceOptions();
sourceOptions.formatHint = "image/png";
ImageSource imageSource = ImageSource.create(resource, sourceOptions);
pixelMap = imageSource.createPixelmap(null);


ImagePacker imagePacker = ImagePacker.create();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImagePacker.PackingOptions packingOptions = new ImagePacker.PackingOptions();
imagePacker.initializePacking(byteArrayOutputStream, packingOptions);
imagePacker.addImage(pixelMap);
imagePacker.finalizePacking();
byte[] bytes = byteArrayOutputStream.toByteArray();
base64String = Base64.getEncoder().encodeToString(bytes);

 

---------------

 

图像编码就是将PixelMap图像编码成不同存档格式图片,用于后续其他处理,比如保存、传输等。当前仅支持JPEG格式。

 

public static class PackingOptions {
    public String format = "image/jpeg";
    public int numberHint = 1;
    public int quality = 100;

    public PackingOptions() {
        throw new RuntimeException("Stub!");
    }
}

PixelMap
ImagePacker
Base64
2021-11-11 14:59:18
浏览
已于2021-11-11 15:05:47修改
收藏 0
回答 3
待解决
回答 3
按赞同
/
按时间
wx60bdd8df940d0
5

RawFileEntry rawFileEntry = getContext().getResourceManager().getRawFileEntry("resources/rawfile/ccdraw/assets/symbol_PLA/commandorgan/6.png");
Resource resource = rawFileEntry.openRawFile();
byte[]  bytes = new byte[resource.available()];
resource.read(bytes);
result_base64 = Base64.getEncoder().encodeToString(bytes);

分享
微博
QQ
微信
回复
2021-11-19 11:46:33
红叶亦知秋
4

目前不支持png 格式 ,只支持jpg格式

分享
微博
QQ
微信
回复
2021-11-16 15:34:42
wx60bdd8df940d0
2

谢谢,问题已解决。

分享
微博
QQ
微信
回复
2021-11-19 11:44:52
相关问题
音视频都支持哪些编码格式
226浏览 • 1回复 待解决
如何用PixelMap处理图片
626浏览 • 1回复 待解决
png图片使用Image组件加载出现锯齿
654浏览 • 1回复 待解决
如何保存一张PNG图片到相册中
703浏览 • 1回复 待解决
希望fs.write支持utf-8之外的编码格式
559浏览 • 1回复 待解决
js canvas转base64编码图片不全
9253浏览 • 1回复 待解决
如何读取相册中的图片
251浏览 • 1回复 待解决
怎么把PixelMap图片转BASE64
8059浏览 • 1回复 待解决
图片编解码能力支持哪些格式
853浏览 • 1回复 待解决
是下载成png,当图片来引用吗?
1211浏览 • 1回复 待解决
如何将图片PixelMap压缩到指定大小
649浏览 • 1回复 待解决
图片编解码支持的格式有哪些
754浏览 • 1回复 待解决
鸿蒙明确支持的图片格式有哪些?
4516浏览 • 1回复 待解决
HarmonyOS是否.9 图片
684浏览 • 1回复 待解决