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!");
}
}
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);
目前不支持png 格式 ,只支持jpg格式
谢谢,问题已解决。