2015-05-18 207 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方案。