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
相关问题
js canvas转base64编码图片不全
8288浏览 • 1回复 待解决
图片编解码能力支持哪些格式
157浏览 • 1回复 待解决
怎么把PixelMap图片转BASE64
7153浏览 • 1回复 待解决
图片编解码支持的格式有哪些
89浏览 • 1回复 待解决
鸿蒙明确支持的图片格式有哪些?
3686浏览 • 1回复 待解决
是下载成png,当图片来引用吗?
605浏览 • 1回复 待解决
如何通过代码随意修改锁屏图片?
3603浏览 • 1回复 待解决
如何显示通过网络加载的图片
665浏览 • 1回复 待解决
HI3516dv300 可以行手势识别嘛
3961浏览 • 1回复 待解决
求鸿蒙视频编码解码的具体demo
4882浏览 • 1回复 待解决
是否可以同时启动多个编码
165浏览 • 1回复 待解决