2015-05-18 132 views
0

我試圖從現有URI創建位圖,旋轉位圖並將其保存到與JPEG文件相同的位置。這是嘗試過多種解決方案後,我當前的代碼:從URI旋轉圖像並將旋轉圖像保存到同一位置

try { 
    // Get the Bitmap from the known URI. This seems to work. 
    Bitmap bmp = MediaStore.Images.Media.getBitmap(this.getContentResolver(), this.currUserImgUri); 

    // Rotate the Bitmap thanks to a rotated matrix. This seems to work. 
    Matrix matrix = new Matrix(); 
    matrix.postRotate(-90); 
    bmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, true); 

    // Create an output stream which will write the Bitmap bytes to the file located at the URI path. 
    File imageFile = new File(this.currUserImgUri.getPath()); 
    FileOutputStream fOut = new FileOutputStream(imageFile); // --> here an Exception is catched; see below. 
    // The following doesn't work neither: 
    // FileOutputStream fOut = new FileOutputStream(this.currUserImgUri.getPath()); 

    // Write the compressed file into the output stream 
    bmp.compress(Bitmap.CompressFormat.JPEG, 85, fOut); 
    fOut.flush(); 
    fOut.close(); 

} catch (FileNotFoundException e1) { 
    e1.printStackTrace(); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 

該逮住例外如下:

java.io.FileNotFoundException:/外部/圖像/媒體/ 8439:打開失敗:ENOENT (沒有這樣的文件或目錄)

任何人都可以向我解釋如果我剛創建它並有權訪問它的URI,該文件不存在嗎?

也許我會對它有所錯?在這種情況下,將旋轉後的圖像保存到基於其URI的相同位置的正確方法是什麼?

+0

鏈接您的AndroidManifest.xml權限等,可能會失去一個權限 –

回答

3

嘿,你可以這樣寫位圖文件使用。

// Rotate the Bitmap thanks to a rotated matrix. This seems to work. 
    Matrix matrix = new Matrix(); 
    matrix.postRotate(90); 
    bmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, true); 
    //learn content provider for more info 
    os=getContentResolver().openOutputStream(uri); 
     bmp.compress(Bitmap.CompressFormat.PNG,100,os); 

不要忘記刷新並關閉輸出流。 實際上內容提供商有它自己的uri方案。