簡體   English   中英

如何將uri圖像轉換為canvas ondraw方法

[英]how to convert uri image into canvas ondraw method

我正在從圖庫中搜索圖像並顯示。現在我想在onDraw(Canvas canvas)顯示圖像。我該怎么做。請幫助我。 提前致謝

selectedImageUri = data.getData();
                        selectedImagePath = getPath(selectedImageUri);
                        Toast.makeText(getBaseContext(),"selected"+selectedImagePath,Toast.LENGTH_LONG).show();
                        System.out.println("Image Path : " + selectedImagePath);
                        img.setImageURI(selectedImageUri);

uri在這里選擇了ImageUri;

我的OnDraw(canvas Canvas)代碼:

Bitmap myBitmap1 = BitmapFactory.decodeResource(getResources(),selectedImageUri);

我的錯誤訊息

BitmapFactory類型的方法encodeResource(Resources,int)不適用於參數(Resources,Uri)

從選擇器返回的路徑是Uri,並且您試圖將其作為資源ID(即int)加載。 從getData()返回的路徑可以是直接指向SD卡上文件的文件路徑,也可以是MediaStore Uri。 如果應用程序將文件保存到磁盤,並且不使用任何MediaStore api方法將其插入MediaStore db,那么您將獲得文件路徑。 否則,您將獲得MediaStore Uri。 由於這個原因,我使用了一個包裝器方法來確定它是哪一個並返回實際路徑:

public static String getRealPathFromURI(Activity activity, Uri contentUri) {    


    String realPath = null;

    // Check for valid file path
    File f = new File(contentUri.getPath());
    if(f.exists())
        realPath = contentUri.getPath();
    // Check for valid MediaStore path
    else
    {           
        String[] proj = { MediaStore.Images.Media.DATA };
        Cursor cursor = activity.managedQuery(contentUri, proj, null, null, null);
        if(cursor != null)
        {
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            realPath = cursor.getString(column_index);
            cursor.close();
        }
    }
    return realPath;
}

一旦有了,就可以從BitmapFactory將其作為流加載:

注意這里省略了很多代碼,因此您可能會遺漏一些東西,但這應該可以為您提供一般方法

    FileInputStream in = null;
    BufferedInputStream buffer = null;
    Bitmap image = null;

    try
    {
        in = new FileInputStream(path);
        buffer = new BufferedInputStream(in);
        image = BitmapFactory.decodeStream(buffer);
    }
    catch (FileNotFoundException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    finally
    {
        try
        {
            if(in != null)
                in.close();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try
        {
            if(buffer != null)
                buffer.close();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM