鴻蒙跳轉到相簿或者檔案選擇圖片並顯示到Image控制元件中

華為開發者論壇發表於2021-06-04

今天有個壇友問跳轉到檔案和相簿如何將選擇的圖片讀取出來在Image控制元件中顯示,我這裡分享一下解決思路。

首先當然是建個佈局頁面,頁面上放個按鈕和圖片控制元件,如下程式碼

<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
    xmlns:ohos="
    ohos:height="match_parent"
    ohos:width="match_parent"
    ohos:orientation="vertical">
    <Button
        ohos:id="$+id:btnChooseImg"
        ohos:height="match_content"
        ohos:width="match_content"
        ohos:text="選擇圖片"
        ohos:text_size="40vp"
        ohos:background_element="gray"></Button>
    <Image
        ohos:id="$+id:showChooseImg"
        ohos:height="match_content"
        ohos:width="match_content"
        ></Image>
</DirectionalLayout>

然後看一下後臺程式碼,後代主要用到DataAbility去訪問圖片,訪問圖片我們需要申請ohos.permission.READ_USER_STORAGE許可權,程式碼如下

package com.example.phonetest.slice;
import com.example.phonetest.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Button;
import ohos.agp.components.Image;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.photokit.metadata.AVStorage;
import ohos.utils.net.Uri;
import java.io.File;
import java.io.FileDescriptor;
public class ChooseImageTestSlice extends AbilitySlice {
    static final HiLogLabel label = new HiLogLabel(HiLog.LOG_APP, 0x0001, "選擇圖片測試");
    private final int imgRequestCode=1123;
    Image showChooseImg=null;
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_choose_image_test);
        //獲取儲存許可權
        requestPermissionsFromUser(new String[]{"ohos.permission.READ_USER_STORAGE"},imgRequestCode);
        Button btnChooseImg=(Button)findComponentById(ResourceTable.Id_btnChooseImg);
        btnChooseImg.setClickedListener(c->{
            //選擇圖片
            selectPic();
        });
        showChooseImg=(Image)findComponentById(ResourceTable.Id_showChooseImg);
    }
    private void selectPic() {
        Intent intent = new Intent();
        Operation opt=new Intent.OperationBuilder().withAction("android.intent.action.GET_CONTENT").build();
        intent.setOperation(opt);
        intent.addFlags(Intent.FLAG_NOT_OHOS_COMPONENT);
        intent.setType("image/*");
        startAbilityForResult(intent, imgRequestCode);
    }
    @Override
    protected void onAbilityResult(int requestCode, int resultCode, Intent resultData) {
        if(requestCode==imgRequestCode)
        {
            HiLog.info(label,"選擇圖片getUriString:"+resultData.getUriString());
            //選擇的Img對應的Uri
            String chooseImgUri=resultData.getUriString();
            HiLog.info(label,"選擇圖片getScheme:"+chooseImgUri.substring(chooseImgUri.lastIndexOf('/')));
            //定義資料能力幫助物件
            DataAbilityHelper helper=DataAbilityHelper.creator(getContext());
            //定義圖片來源物件
            ImageSource imageSource = null;
            //獲取選擇的Img對應的Id
            String chooseImgId=null;
            //如果是選擇檔案則getUriString結果為content://com.android.providers.media.documents/document/image%3A30,其中%3A是":"的URL編碼結果,後面的數字就是image對應的Id
            //如果選擇的是相簿則getUriString結果為content://media/external/images/media/30,最後就是image對應的Id
            //這裡需要判斷是選擇了檔案還是相簿
            if(chooseImgUri.lastIndexOf("%3A")!=-1){
                chooseImgId = chooseImgUri.substring(chooseImgUri.lastIndexOf("%3A")+3);
            }
            else {
                chooseImgId = chooseImgUri.substring(chooseImgUri.lastIndexOf('/')+1);
            }
            //獲取圖片對應的uri,由於獲取到的字首是content,我們替換成對應的dataability字首
            Uri uri=Uri.appendEncodedPathToUri(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI,chooseImgId);
            HiLog.info(label,"選擇圖片dataability路徑:"+uri.toString());
            try {
                //讀取圖片
                FileDescriptor fd = helper.openFile(uri, "r");
                imageSource = ImageSource.create(fd, null);
                //建立點陣圖
                PixelMap pixelMap = imageSource.createPixelmap(null);
                //設定圖片控制元件對應的點陣圖
                showChooseImg.setPixelMap(pixelMap);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (imageSource != null) {
                    imageSource.release();
                }
            }
        }
    }
    @Override
    public void onActive() {
        super.onActive();
    }
    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}

我看一下執行結果

記得提前拍兩張照片,因為模擬器裡面一開始是沒有照片的


原文連結: https://developer.huawei.com/consumer/cn/forum/topic/0202550313178650107?fid=0101303901040230869

原作者: Kak_zhou

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69970551/viewspace-2775418/,如需轉載,請註明出處,否則將追究法律責任。

相關文章