2011-11-28 88 views
26

我正在嘗試使用來自Android的SHARE INTENT與Facebook,Twitter等分享圖像。如何將位圖轉換爲Uri?

我發現代碼的圖像發送到共享的意圖,但是這個代碼所需要的位圖的URI:fullSizeImageUri

這是全碼:

private void startShareMediaActivity(Bitmap image) { 
    boolean isVideo=false; 
    String mimeType="bmp"; 
    Uri fullSizeImageUri=null; 
    Intent intent = new Intent(); 
    intent.setAction(Intent.ACTION_SEND); 
    intent.setType(mimeType); 
    intent.putExtra(Intent.EXTRA_STREAM, fullSizeImageUri); 
    try { 
     startActivity(Intent.createChooser(intent, (isVideo ? "video" : "image"))); 
    } catch (android.content.ActivityNotFoundException ex) { } 
} 

請,有人可以幫助我將位圖轉換爲Uri?

謝謝

回答

17
String FILENAME = "image.png"; 
String PATH = "/mnt/sdcard/"+ FILENAME; 
File f = new File(PATH); 
Uri yourUri = Uri.fromFile(f); 
+1

解析總是採取一個字符串不是文件的參數。下次閱讀關於功能的細節或者測試它們。 – Arkde

+2

對不起Arkde小混亂任何方式感謝提醒 –

+4

我們不能得到Uri沒有保存位圖 – Prasad

0

那麼你不能將一個位圖文件轉換成一個uri。閱讀關於URI的更多信息here

URI是統一資源標識符。但是,你可以將位圖中的絕對或相對URI這樣

Absolute: http://android.com/yourImage.bmp 
Relative: yourImage.bmp 
+0

那麼如何才能實現我的需要的圖像質量?不可能? – NullPointerException

+0

我想你必須重新思考你的方式來看看這個...檢查Facebook和Twitter的APIS,看看你如何實現圖像共享 – Arkde

50

這裏是科林的博客誰建議簡單的方法,以位圖轉換爲開放的Click here

public Uri getImageUri(Context inContext, Bitmap inImage) { 
    ByteArrayOutputStream bytes = new ByteArrayOutputStream(); 
    inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes); 
    String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null); 
    return Uri.parse(path); 
} 
+5

但如何刪除圖像插入?它會在文件夾中創建大量圖像。 – Noman

+4

不適用於KitKat及更高版本 – DroidLearner

+0

不適用於Android Wear – Lunatikul

0

上述解決方案使用媒體商店並將圖像存儲在用戶主圖像文件夾中,通過圖庫/照片查看器進行查看。該解決方案將其作爲臨時文件存儲在您的應用數據中。在這個例子中,圖像是一個位圖,標題是圖像文件名稱的字符串。

File tempDir= Environment.getExternalStorageDirectory(); 
    tempDir=new File(tempDir.getAbsolutePath()+"/.temp/"); 
    tempDir.mkdir(); 
    File tempFile = File.createTempFile(title, ".jpg", tempDir); 
    ByteArrayOutputStream bytes = new ByteArrayOutputStream(); 
    inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes); 
    byte[] bitmapData = bytes.toByteArray(); 

    //write the bytes in file 
    FileOutputStream fos = new FileOutputStream(tempFile); 
    fos.write(bitmapData); 
    fos.flush(); 
    fos.close(); 
    return Uri.fromFile(tempFile); 
0
String picName = "pic.jpg"; 
     String PATH = Environment.getExternalStorageDirectory().getPath()+ picName; 
     File f = new File(PATH); 
     Uri yourUri = Uri.fromFile(f); 
-1

傳位圖和compressFormat像(PNG,JPG等),並以百分比

public Uri getImageUri(Bitmap src, Bitmap.CompressFormat format, int quality) { 
    ByteArrayOutputStream os = new ByteArrayOutputStream(); 
    src.compress(format, quality, os); 

    String path = MediaStore.Images.Media.insertImage(getContentResolver(), src, "title", null); 
    return Uri.parse(path); 
} 
+0

path可以爲null,所以你的代碼會在Uri.parse(path) –

+0

上崩潰,你檢查路徑是否爲null。你通過Uri後 –