儲存圖片到相簿及圖片變黑問題
阿新 • • 發佈:2018-11-02
今天寫一下儲存圖片到手機相簿的功能!
整個儲存圖片的程式碼如下:
public void saveImageToGallery(Context context, Bitmap bmp) {
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
return;
}
// 首先儲存圖片
File appDir = Environment.getExternalStoragePublicDirectory (Environment.DIRECTORY_DCIM).getAbsoluteFile();
if (!appDir.exists()) {
appDir.mkdir();
}
String fileName = System.currentTimeMillis() + ".png";
File file = new File(appDir, fileName);
try {
FileOutputStream fos = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
} catch (IOException e) {
e.printStackTrace();
return;
}
try {
MediaStore.Images .Media.insertImage(context.getContentResolver(),
file.getAbsolutePath(), fileName, null);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// 最後通知相簿更新
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getAbsolutePath())));
}
長按圖片的事件
imgView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
saveImageToGallery(MainActivity.this, bitmap);
return true;//true代表消費了該事件,不在往下傳遞,如果返回false,會觸發onclicklistener時間
}
});
特別注意這點:呼叫getDrawingCache()前先要測量,否則的話得到的bitmap為null,也就是儲存到相簿裡圖片會變黑的問題
imgView = findViewById(R.id.icon);
imgView.setDrawingCacheEnabled(true);
imgView.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
imgView.layout(0, 0, imgView.getMeasuredWidth(), imgView.getMeasuredHeight());
bitmap = Bitmap.createBitmap(imgView.getDrawingCache());
imgView.setDrawingCacheEnabled(false);