简体   繁体   English

从ImageView保存图像

[英]Save Image from ImageView

I tried to save an image from an ImageView into the gallery. 我试图将图像从ImageView保存到图库中。 I tried it like this: 我这样尝试过:

Bitmap bitmap = imageView.getDrawingCache();  

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

But it won't work :/ No errong, nothing :/ Can someone help me? 但这是行不通的:/没有错,什么都没有:/有人可以帮助我吗?

Try this: 尝试这个:

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

Helpers: 帮手:

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM