Chr*_*pix 457 android bitmap save
我正在开发一个功能,从Web服务器下载图像,将其显示在屏幕上,如果用户希望保留图像,请将其保存在某个文件夹中的SD卡上.是否有一种简单的方法来获取位图并将其保存到我选择的文件夹中的SD卡?
我的问题是我可以下载图像,将其作为位图显示在屏幕上.我能够找到将图像保存到特定文件夹的唯一方法是使用FileOutputStream,但这需要一个字节数组.我不确定如何从Bitmap转换(如果这是正确的方法)到字节数组,所以我可以使用FileOutputStream来写入数据.
我有另一个选择是使用MediaStore:
MediaStore.Images.Media.insertImage(getContentResolver(), bm,
barcodeNumber + ".jpg Card Image", barcodeNumber + ".jpg Card Image");
Run Code Online (Sandbox Code Playgroud)
哪个可以保存到SD卡,但不允许您自定义文件夹.
Ulr*_*ler 899
try (FileOutputStream out = new FileOutputStream(filename)) {
bmp.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance
// PNG is a lossless format, the compression factor (100) is ignored
} catch (IOException e) {
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
Joa*_*inG 131
您应该使用该Bitmap.compress()
方法将位图保存为文件.它将压缩(如果使用的格式允许)你的图片并将其推入OutputStream.
下面是一个通过getImageBitmap(myurl)
它获得的Bitmap实例的示例,可以压缩为压缩率为85%的JPEG:
// Assume block needs to be inside a Try/Catch block.
String path = Environment.getExternalStorageDirectory().toString();
OutputStream fOut = null;
Integer counter = 0;
File file = new File(path, "FitnessGirl"+counter+".jpg"); // the File to save , append increasing numeric counter to prevent files from getting overwritten.
fOut = new FileOutputStream(file);
Bitmap pictureBitmap = getImageBitmap(myurl); // obtaining the Bitmap
pictureBitmap.compress(Bitmap.CompressFormat.JPEG, 85, fOut); // saving the Bitmap to a file compressed as a JPEG with 85% compression rate
fOut.flush(); // Not really required
fOut.close(); // do not forget to close the stream
MediaStore.Images.Media.insertImage(getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName());
Run Code Online (Sandbox Code Playgroud)
小智 37
outStream = new FileOutputStream(file);
Run Code Online (Sandbox Code Playgroud)
将在未经许可的情况下在AndroidManifest.xml中抛出异常(至少在os2.2中):
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Run Code Online (Sandbox Code Playgroud)
小智 23
内部onActivityResult
:
String filename = "pippo.png";
File sd = Environment.getExternalStorageDirectory();
File dest = new File(sd, filename);
Bitmap bitmap = (Bitmap)data.getExtras().get("data");
try {
FileOutputStream out = new FileOutputStream(dest);
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
以下是将位图保存到文件的示例代码:
public static File savebitmap(Bitmap bmp) throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 60, bytes);
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "testimage.jpg");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.close();
return f;
}
Run Code Online (Sandbox Code Playgroud)
现在调用此函数将位图保存到内部存储器.
File newfile = savebitmap(bitmap)
;
我希望它会对你有所帮助.快乐的编码生活.
Bitmap bbicon;
bbicon=BitmapFactory.decodeResource(getResources(),R.drawable.bannerd10);
//ByteArrayOutputStream baosicon = new ByteArrayOutputStream();
//bbicon.compress(Bitmap.CompressFormat.PNG,0, baosicon);
//bicon=baosicon.toByteArray();
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
OutputStream outStream = null;
File file = new File(extStorageDirectory, "er.PNG");
try {
outStream = new FileOutputStream(file);
bbicon.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch(Exception e) {
}
Run Code Online (Sandbox Code Playgroud)
我知道这个问题很老,但现在我们可以在WRITE_EXTERNAL_STORAGE
未经许可的情况下达到相同的结果。而不是我们可以使用文件提供程序。
private fun storeBitmap(bitmap: Bitmap, file: File){
requireContext().getUriForFile(file)?.run {
requireContext().contentResolver.openOutputStream(this)?.run {
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, this)
close()
}
}
}
Run Code Online (Sandbox Code Playgroud)
如何从提供程序检索文件?
fun Context.getUriForFile(file: File): Uri? {
return FileProvider.getUriForFile(
this,
"$packageName.fileprovider",
file
)
}
Run Code Online (Sandbox Code Playgroud)
也不要忘记provider
在 Android 中注册您的manifest
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"/>
</provider>
Run Code Online (Sandbox Code Playgroud)
小智 5
我还想保存一张照片.但我的问题(?)是我想从我绘制的位图中保存它.
我这样做了:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.save_sign:
myView.save();
break;
}
return false;
}
public void save() {
String filename;
Date date = new Date(0);
SimpleDateFormat sdf = new SimpleDateFormat ("yyyyMMddHHmmss");
filename = sdf.format(date);
try{
String path = Environment.getExternalStorageDirectory().toString();
OutputStream fOut = null;
File file = new File(path, "/DCIM/Signatures/"+filename+".jpg");
fOut = new FileOutputStream(file);
mBitmap.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
fOut.flush();
fOut.close();
MediaStore.Images.Media.insertImage(getContentResolver()
,file.getAbsolutePath(),file.getName(),file.getName());
}catch (Exception e) {
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
我发现发送PNG和透明度的方式.
String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() +
"/CustomDir";
File dir = new File(file_path);
if(!dir.exists())
dir.mkdirs();
String format = new SimpleDateFormat("yyyyMMddHHmmss",
java.util.Locale.getDefault()).format(new Date());
File file = new File(dir, format + ".png");
FileOutputStream fOut;
try {
fOut = new FileOutputStream(file);
yourbitmap.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
Uri uri = Uri.fromFile(file);
Intent intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setType("image/*");
intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "");
intent.putExtra(android.content.Intent.EXTRA_TEXT, "");
intent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(intent,"Sharing something")));
Run Code Online (Sandbox Code Playgroud)
将位图保存到图库而不压缩。
private File saveBitMap(Context context, Bitmap Final_bitmap) {
File pictureFileDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Your Folder Name");
if (!pictureFileDir.exists()) {
boolean isDirectoryCreated = pictureFileDir.mkdirs();
if (!isDirectoryCreated)
Log.i("TAG", "Can't create directory to save the image");
return null;
}
String filename = pictureFileDir.getPath() + File.separator + System.currentTimeMillis() + ".jpg";
File pictureFile = new File(filename);
try {
pictureFile.createNewFile();
FileOutputStream oStream = new FileOutputStream(pictureFile);
Final_bitmap.compress(Bitmap.CompressFormat.PNG, 100, oStream);
oStream.flush();
oStream.close();
Toast.makeText(Full_Screen_Activity.this, "Save Image Successfully..", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Log.i("TAG", "There was an issue saving the image.");
}
scanGallery(context, pictureFile.getAbsolutePath());
return pictureFile;
}
private void scanGallery(Context cntx, String path) {
try {
MediaScannerConnection.scanFile(cntx, new String[]{path}, null, new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Toast.makeText(Full_Screen_Activity.this, "Save Image Successfully..", Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
e.printStackTrace();
Log.i("TAG", "There was an issue scanning gallery.");
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
466994 次 |
最近记录: |