将位图转换为文件

我明白,使用BitmapFactory可以将文件转换为位图,但有什么办法将位图图像转换为文件?

尝试这个:

 bitmap.compress(Bitmap.CompressFormat.PNG, quality, outStream); 

看到这个

希望它能帮助你:

 //create a file to write bitmap data File f = new File(context.getCacheDir(), filename); f.createNewFile(); //Convert bitmap to byte array Bitmap bitmap = your bitmap; ByteArrayOutputStream bos = new ByteArrayOutputStream(); bitmap.compress(CompressFormat.PNG, 0 /*ignored for PNG*/, bos); byte[] bitmapdata = bos.toByteArray(); //write the bytes in file FileOutputStream fos = new FileOutputStream(f); fos.write(bitmapdata); fos.flush(); fos.close(); 
 File file = new File("path"); OutputStream os = new BufferedOutputStream(new FileOutputStream(file)); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os); os.close(); 

Bitmap转换为File需要在后台完成(不在主线程中),如果bitmap很大,它会特别挂起用户界面

 File file; public class fileFromBitmap extends AsyncTask<Void, Integer, String> { Context context; Bitmap bitmap; String path_external = Environment.getExternalStorageDirectory() + File.separator + "temporary_file.jpg"; public fileFromBitmap(Bitmap bitmap, Context context) { this.bitmap = bitmap; this.context= context; } @Override protected void onPreExecute() { super.onPreExecute(); // before executing doInBackground // update your UI // exp; make progressbar visible } @Override protected String doInBackground(Void... params) { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes); file = new File(Environment.getExternalStorageDirectory() + File.separator + "temporary_file.jpg"); try { FileOutputStream fo = new FileOutputStream(file); fo.write(bytes.toByteArray()); fo.flush(); fo.close(); } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); // back to main thread after finishing doInBackground // update your UI or take action after // exp; make progressbar gone sendFile(file); } } 

调用它

 new fileFromBitmap(my_bitmap, getApplicationContext()); 

你必须使用onPostExecutefile

要更改要存储在caching中的file目录replace行:

  file = new File(Environment.getExternalStorageDirectory() + File.separator + "temporary_file.jpg"); 

与:

 file = new File(context.getCacheDir(), "temporary_file.jpg");