ボタンをクリックしてユーザーのSDカードに画像を保存する方法を知りたいです。誰かがそれを行う方法を教えてくれませんか。画像は .png 形式で、drawable ディレクトリに保存されます。その画像をユーザーのSDカードに保存するボタンをプログラムしたいと思います。
23631 次
3 に答える
43
ファイル(あなたの場合は画像)を保存するプロセスはここで説明されています:save-file-to-sd-card
drawble リソースから sdcard に画像を保存しています:
ドローアブルに ic_launcher という画像があるとします。次に、この画像から次のようなビットマップ オブジェクトを取得します。
Bitmap bm = BitmapFactory.decodeResource( getResources(), R.drawable.ic_launcher);
SD カードへのパスは、次を使用して取得できます。
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
次に、ボタンをクリックして次を使用してSDカードに保存します。
File file = new File(extStorageDirectory, "ic_launcher.PNG");
FileOutputStream outStream = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
android.permission.WRITE_EXTERNAL_STORAGE
許可を追加することを忘れないでください。
ドローアブルから保存するために変更されたファイルは次のとおりです: SaveToSd 、完全なサンプル プロジェクト: SaveImage
于 2012-05-12T06:17:01.840 に答える
3
その質問には本当の解決策はないと思います。それを行う唯一の方法は、次のように sd_card キャッシュディレクトリからコピーして起動することです。
Bitmap bm = BitmapFactory.decodeResource(getResources(), resourceId);
File f = new File(getExternalCacheDir()+"/image.png");
try {
FileOutputStream outStream = new FileOutputStream(f);
bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (Exception e) { throw new RuntimeException(e); }
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(f), "image/png");
startActivity(intent);
// NOT WORKING SOLUTION
// Uri path = Uri.parse("android.resource://" + getPackageName() + "/" + resourceId);
// Intent intent = new Intent();
// intent.setAction(android.content.Intent.ACTION_VIEW);
// intent.setDataAndType(path, "image/png");
// startActivity(intent);
于 2014-03-18T18:43:18.157 に答える
0
Kotlinを使用する場合は、次のようにできます。
val mDrawable: Drawable? = baseContext.getDrawable(id)
val mbitmap = (mDrawable as BitmapDrawable).bitmap
val mfile = File(externalCacheDir, "myimage.PNG")
try {
val outStream = FileOutputStream(mfile)
mbitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream)
outStream.flush()
outStream.close()
} catch (e: Exception) {
throw RuntimeException(e)
}
于 2021-11-21T13:42:05.197 に答える