快速开始
更新时间:2023-07-26
下面介绍Android端HEIF图片解码SDK的基本用法,以解码本地图片为例。
// 读取Asset中的图片
private static InputStream loadInputStreamFromAssetFile(Context context, String fileName){
AssetManager am = context.getAssets();
try {
return am.open(fileName);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private static ByteArrayOutputStream readDataFromInpuStream(InputStream inputStream) {
try {
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
return output;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
// 使用百度智能云HEIF图片加载SDK进行解码
private void decodeImageWithBaidu(byte[] heifData) {
ImageView image = mRootView.findViewById(R.id.image_bdcloud);
try {
// 获取HEIF图片元数据
HeifInfo heifInfo = new HeifInfo();
HeifDecoder.getInfo(heifData.length, heifData, heifInfo);
// 当前仅支持单帧静图解码
HeifSize heifSize = heifInfo.getFrameList().get(0);
// 获取HEIF图片宽高
int width = heifSize.getWidth();
int height = heifSize.getHeight();
// 创建Android Bitmap
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
// 将HEIF图片解码为Bitmap
HeifDecoder.toRgba(heifData.length, heifData, bitmap);
} catch (Exception e) {
e.printStackTrace();
}
return;
}
// 完整业务流程展示
private void showLocalImage() {
InputStream inputStream = loadInputStreamFromAssetFile(mContext, DEFAULT_LOCAL_IMG_URL);
if (inputStream == null) {
return;
}
ByteArrayOutputStream baos = readDataFromInpuStream(inputStream);
if (baos == null) {
return;
}
byte[] heifData = baos.toByteArray();
decodeImageWithBaidu(heifData);
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
return;
}
在Demo工程的LocalImageFragment.java中对上述流程做了详细的展示,可以参考。