【问题标题】:Save Image from ImageView从 ImageView 保存图像
【发布时间】:2016-08-12 03:19:50
【问题描述】:

我尝试将 ImageView 中的图像保存到图库中。我试过这样:

Bitmap bitmap = imageView.getDrawingCache();  

MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, "" , "");

但它不起作用:/没有错,什么都没有:/有人可以帮助我吗?

【问题讨论】:

  • 这里有一个很好的示例stackoverflow.com/questions/9078715/…
  • 嗯它只是将它保存到SD卡,而不是我可以在图库中看到它并且文件已创建但您无法查看图片:/
  • 检查this。我已经给出了解决方案。希望这会有所帮助!

标签: java android imageview image


【解决方案1】:

试试这个:

FileOutputStream fos= null;
File file = getDisc();
if(!file.exists() && !file.mkdirs()) {
    //Toast.makeText(this, "Can't create directory to store image", Toast.LENGTH_LONG).show();
    //return;
    print("file not created");
    return;
}
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyymmsshhmmss");
String date = simpleDateFormat.format(new Date());
String name = "FileName"+date+".jpg";
String file_name = file.getAbsolutePath()+"/"+name;
File new_file = new File(file_name);
print("new_file created");
try {
    fos= new FileOutputStream(new_file);
    Bitmap bitmap = viewToBitmap(iv, iv.getWidth(), iv.getHeight() );
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
    Toast.makeText(this, "Save success", Toast.LENGTH_LONG).show();
    fos.flush();
    fos.close();
} catch (FileNotFoundException e) {
    print("FNF");
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
refreshGallery(new_file);

助手:

public void refreshGallery(File file){
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(file));
sendBroadcast(intent);
}

private File getDisc(){
String t= getCurrentDateAndTime();
File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
return new File(file, "ImageDemo");
}

private String getCurrentDateAndTime() {
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
String formattedDate = df.format(c.getTime());
return formattedDate;

public static Bitmap viewToBitmap(View view, int width, int height) {
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-26
    • 1970-01-01
    • 2012-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-18
    相关资源
    最近更新 更多