快速开始
更新时间:2023-07-26
下面介绍Android端HEIF图片解码SDK的基本用法,以解码本地图片为例。
Java
1// 读取Asset中的图片
2private static InputStream loadInputStreamFromAssetFile(Context context, String fileName){
3 AssetManager am = context.getAssets();
4 try {
5 return am.open(fileName);
6 } catch (IOException e) {
7 e.printStackTrace();
8 }
9 return null;
10}
11
12private static ByteArrayOutputStream readDataFromInpuStream(InputStream inputStream) {
13 try {
14 ByteArrayOutputStream output = new ByteArrayOutputStream();
15 byte[] buffer = new byte[8192];
16 int bytesRead;
17 while ((bytesRead = inputStream.read(buffer)) != -1) {
18 output.write(buffer, 0, bytesRead);
19 }
20 return output;
21 } catch (IOException e) {
22 e.printStackTrace();
23 }
24 return null;
25}
26
27// 使用百度智能云HEIF图片加载SDK进行解码
28private void decodeImageWithBaidu(byte[] heifData) {
29 ImageView image = mRootView.findViewById(R.id.image_bdcloud);
30 try {
31 // 获取HEIF图片元数据
32 HeifInfo heifInfo = new HeifInfo();
33 HeifDecoder.getInfo(heifData.length, heifData, heifInfo);
34 // 当前仅支持单帧静图解码
35 HeifSize heifSize = heifInfo.getFrameList().get(0);
36 // 获取HEIF图片宽高
37 int width = heifSize.getWidth();
38 int height = heifSize.getHeight();
39 // 创建Android Bitmap
40 Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
41 // 将HEIF图片解码为Bitmap
42 HeifDecoder.toRgba(heifData.length, heifData, bitmap);
43 } catch (Exception e) {
44 e.printStackTrace();
45 }
46 return;
47}
48
49// 完整业务流程展示
50private void showLocalImage() {
51 InputStream inputStream = loadInputStreamFromAssetFile(mContext, DEFAULT_LOCAL_IMG_URL);
52 if (inputStream == null) {
53 return;
54 }
55
56 ByteArrayOutputStream baos = readDataFromInpuStream(inputStream);
57 if (baos == null) {
58 return;
59 }
60
61 byte[] heifData = baos.toByteArray();
62 decodeImageWithBaidu(heifData);
63
64 try {
65 inputStream.close();
66 } catch (IOException e) {
67 e.printStackTrace();
68 }
69
70 try {
71 baos.close();
72 } catch (IOException e) {
73 e.printStackTrace();
74 }
75 return;
76}
在Demo工程的LocalImageFragment.java中对上述流程做了详细的展示,可以参考。