2012-01-10 76 views
2

这个问题很简单,我们可以:保存位为JPEG文件

public static void writePhotoJpg(Bitmap data, String pathName) { 
    File file = new File(pathName); 
    try { 
     file.createNewFile(); 
     // BufferedOutputStream os = new BufferedOutputStream(
     // new FileOutputStream(file)); 

     FileOutputStream os = new FileOutputStream(file); 
     data.compress(Bitmap.CompressFormat.JPEG, 100, os); 
     os.flush(); 
     os.close(); 


    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

但这种方法并非所有的成功:因为“注:并不是所有的格式直接支持所有的位图的configs,所以这是可能的从BitmapFactory返回的位图可能处于不同的位深度,并且/或者可能已经丢失了每个像素的alpha(例如,JPEG仅支持不透明像素)。“在谷歌文件。没有运气,我有这样的问题:在相机预览我用:

private Bitmap printScreen() { 
    View view = this.getWindow().getDecorView(); 
    // if (view.isDrawingCacheEnabled()) { 
    view.setDrawingCacheEnabled(true); 
    Calendar c = Calendar.getInstance(); 
    String date = c.get(Calendar.YEAR) + "-" + (c.get(Calendar.MONTH) + 1) + "-" + c.get(Calendar.DAY_OF_MONTH) + " " + c.get(Calendar.HOUR_OF_DAY) + "-" + c.get(Calendar.MINUTE) + "-" + c.get(Calendar.SECOND); 
    // } 
    view.buildDrawingCache(); 

    Bitmap bmp = view.getDrawingCache(); 

    return bmp ; 
} 

所以当我用setImageBitmap(BMP),看起来非常好,但是当我打开保存JPEG文件是一个黑色的jpeg.so我认为保存方法不好,你能告诉我另一种保存方法吗?的视图或布局

回答

0

使用.getRootView()方法包含此视图中,使用它(例如)mainLayout包含在索引1然后mainlayou.getChildAt(1)一个图像视图来获取该视图。

例如

View v1 = mainLayout.getChildAt(1);  //OR View v1 = mainLayout.getRootView(); 
     v1.setDrawingCacheEnabled(true); 
     Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache()); 
     v1.setDrawingCacheEnabled(false); 
     return bitmap; 

希望对你有帮助...

+0

谢谢你的回答,但没有效果 – pengwang 2012-01-10 09:27:01

+0

我已经尝试过,并为我工作。如果我想拍摄特定视图的屏幕截图并将其保存为位图,则可以使用此视图。 – 2012-01-10 09:31:49

+0

是的,如果使用常见的环境它正确,但使用赶上相机预览它失败,保存文件JPEG是黑色的,但ImageView显示正确 – pengwang 2012-01-10 10:12:43

3

你可以试试这个:

public static final int BUFFER_SIZE = 1024 * 8; 
static void writeExternalToCache(Bitmap bitmap, File file) { 
    try { 
     file.createNewFile(); 
     FileOutputStream fos = new FileOutputStream(file); 
     final BufferedOutputStream bos = new BufferedOutputStream(fos, BUFFER_SIZE); 
     bitmap.compress(CompressFormat.JPEG, 100, bos); 
     bos.flush(); 
     bos.close(); 
     fos.close(); 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 

    } 

} 

它在我的代码,因此,如果它不能正常工作,试图找到错误:

1.位图显示是否正确?

2.其中是位图保存文件?该文件有一些限制?像大小或...

如果错误是你的原因,你可以尝试使用Bitmap.Config.RGB_565再次解码位图。

+0

谢谢你,我会尝试 – pengwang 2012-01-10 10:15:49

+0

对不起,没有effect.i也使用Bitmap.Config.RGB_565 – pengwang 2012-01-11 00:45:21

+0

优秀!但我曾尝试多次使用此代码与失败,因为我错过了一件事...将此权限添加到清单文件中: <使用权限android:name =“android.permission.WRITE_EXTERNAL_STORAGE”/> 谢谢。 – Mehdi 2013-08-14 06:54:23

相关问题