Android Studio - 将Bitmap转换为java.io.File

时间:2016-12-25 11:48:16

标签: java android bitmap java-io

我已经从视频文件中创建了一个视频缩略图。我需要做的是从java.io.File创建Bitmap,以便将缩略图上传到服务器。怎么能实现这个目标?

Bitmap thumb = ThumbnailUtils.createVideoThumbnail(videoFile.getPath(), MediaStore.Video.Thumbnails.FULL_SCREEN_KIND);

File thumbFile = ?

1 个答案:

答案 0 :(得分:0)

可以使用以下代码:

 //create a file to write bitmap data
File f = new File(context.getCacheDir(), filename);

//f.createNewFile(); (No need to call as FileOutputStream will automatically create the file)

//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();

您也可以尝试这种方法:它不会将位图转换为字节数组..

private static void bitmap_to_file(Bitmap bitmap, String name) {
  File filesDir = getAppContext().getFilesDir();
  File imageFile = new File(filesDir, name + ".jpg");

  OutputStream os;
  try {
    os = new FileOutputStream(imageFile);
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
    os.flush();
    os.close();
  } catch (Exception e) {
    Log.e(getClass().getSimpleName(), "Error writing bitmap", e);
  }
}