我正在开发一个从Web服务器下载图像,在屏幕上显示图像的功能,如果用户希望保留图像,请将其保存在某个文件夹中的SD卡上。是否有一种简单的方法来获取位图并将其保存到我选择的文件夹中的SD卡中?
我的问题是我可以下载图像,将其作为位图显示在屏幕上。我能够找到将图像保存到特定文件夹的唯一方法是使用FileOutputStream,但这需要一个字节数组。我不确定如何从Bitmap转换(如果这是正确的方法),所以我可以使用FileOutputStream来写入数据。
我的另一个选择是使用MediaStore:
MediaStore.Images.Media.insertImage(getContentResolver(), bm,
barcodeNumber + ".jpg Card Image", barcodeNumber + ".jpg Card Image");
可以保存到SD卡,但不允许自定义文件夹。
答案 0 :(得分:868)
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();
}
答案 1 :(得分:129)
您应该使用Bitmap.compress()
方法将位图另存为文件。它将压缩(如果使用的格式允许)你的图片并将其推入OutputStream。
以下是通过getImageBitmap(myurl)
获得的Bitmap实例的示例,该实例可以压缩为JPEG,压缩率为85%:</ p>
// 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());
答案 2 :(得分:36)
outStream = new FileOutputStream(file);
将在未经许可的情况下在AndroidManifest.xml中抛出异常(至少在os2.2中):
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
答案 3 :(得分: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();
}
答案 4 :(得分:13)
有些格式,如PNG无损,会忽略质量设置。
答案 5 :(得分:8)
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) {
}
答案 6 :(得分:8)
以下是将位图保存到文件的示例代码:
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;
}
现在调用此函数将位图保存到内部存储器。
File newfile = savebitmap(bitmap)
;
我希望它会对你有所帮助。 快乐的编码生活。
答案 7 :(得分:7)
为什么不用100调用Bitmap.compress
方法(听起来像是无损)?
答案 8 :(得分: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();
}
}
答案 9 :(得分:5)
我发现发送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")));
答案 10 :(得分:2)
为视频创建视频缩略图。如果视频损坏或不支持该格式,则可能返回null。
private void makeVideoPreview() {
Bitmap thumbnail = ThumbnailUtils.createVideoThumbnail(videoAbsolutePath, MediaStore.Images.Thumbnails.MINI_KIND);
saveImage(thumbnail);
}
要在sdcard中保存位图,请使用以下代码
存储图片
private void storeImage(Bitmap image) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
Log.d(TAG,
"Error creating media file, check storage permissions: ");// e.getMessage());
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
获取图像存储路径
/** Create a File for saving an image or video */
private File getOutputMediaFile(){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
+ "/Android/data/"
+ getApplicationContext().getPackageName()
+ "/Files");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
File mediaFile;
String mImageName="MI_"+ timeStamp +".jpg";
mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
return mediaFile;
}
答案 11 :(得分:1)
我知道这个问题很旧,但是现在我们可以在没有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()
}
}
}
如何从提供商处检索文件?
fun Context.getUriForFile(file: File): Uri? {
return FileProvider.getUriForFile(
this,
"$packageName.fileprovider",
file
)
}
也不要忘记在Android provider
中注册您的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>
答案 12 :(得分:1)
一些新设备没有保存位图,所以我解释了一些。
确保您已添加以下权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
并在
下创建xml文件xml
文件夹名称 provider_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path
name="external_files"
path="." />
</paths>
并在AndroidManifest下
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>
然后只需调用saveBitmapFile(passYourBitmapHere)
public static void saveBitmapFile(Bitmap bitmap) throws IOException {
File mediaFile = getOutputMediaFile();
FileOutputStream fileOutputStream = new FileOutputStream(mediaFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, getQualityNumber(bitmap), fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
}
其中
File getOutputMediaFile() {
File mediaStorageDir = new File(
Environment.getExternalStorageDirectory(),
"easyTouchPro");
if (mediaStorageDir.isDirectory()) {
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(Calendar.getInstance().getTime());
String mCurrentPath = mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg";
File mediaFile = new File(mCurrentPath);
return mediaFile;
} else { /// error handling for PIE devices..
mediaStorageDir.delete();
mediaStorageDir.mkdirs();
galleryAddPic(mediaStorageDir);
return (getOutputMediaFile());
}
}
和其他方法
public static int getQualityNumber(Bitmap bitmap) {
int size = bitmap.getByteCount();
int percentage = 0;
if (size > 500000 && size <= 800000) {
percentage = 15;
} else if (size > 800000 && size <= 1000000) {
percentage = 20;
} else if (size > 1000000 && size <= 1500000) {
percentage = 25;
} else if (size > 1500000 && size <= 2500000) {
percentage = 27;
} else if (size > 2500000 && size <= 3500000) {
percentage = 30;
} else if (size > 3500000 && size <= 4000000) {
percentage = 40;
} else if (size > 4000000 && size <= 5000000) {
percentage = 50;
} else if (size > 5000000) {
percentage = 75;
}
return percentage;
}
和
void galleryAddPic(File f) {
Intent mediaScanIntent = new Intent(
"android.intent.action.MEDIA_SCANNER_SCAN_FILE");
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
答案 13 :(得分:1)
您要将位图保存到您选择的目录中。我制作了一个ImageWorker库,使用户可以加载,保存和转换位图/可绘制对象/ base64图像。
Min SDK-14
先决条件
保存位图/可绘制/ Base64
ImageWorker.to(context).
directory("ImageWorker").
subDirectory("SubDirectory").
setFileName("Image").
withExtension(Extension.PNG).
save(sourceBitmap,85)
加载位图
val bitmap: Bitmap? = ImageWorker.from(context).
directory("ImageWorker").
subDirectory("SubDirectory").
setFileName("Image").
withExtension(Extension.PNG).
load()
实施
在项目级别Gradle中
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
在应用程序级别绑定中
dependencies {
implementation 'com.github.1AboveAll:ImageWorker:0.51'
}
您可以在https://github.com/1AboveAll/ImageWorker/blob/master/README.md
上阅读更多内容答案 14 :(得分:1)
在Android 4.4 Kitkat之后,截至2017年Android 4.4及更低版本的份额约为20%且正在减少,因此无法使用File
课程和getExternalStorageDirectory()
保存到SD卡方法。此方法返回您的设备内部存储器和图像保存对每个应用程序可见。您还可以仅保存应用程序专用的图像,并在用户使用openFileOutput()
方法删除您的应用时删除。
从Android 6.0开始,您可以将SD卡格式化为内部存储器,但只能将其格式化为您的设备。(如果您将SD卡格式化为内部存储器,只有您的设备可以访问或查看它的内容)您可以使用其他答案保存到SD卡但如果你想使用可移动的SD卡,你应该阅读下面的答案。
您应该使用存储访问框架来获取文件夹onActivityResult
文件夹的uri以获取用户选择的文件夹,并添加可翻译的持久权限以便在用户重新启动后能够访问文件夹设备。
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
// selectDirectory() invoked
if (requestCode == REQUEST_FOLDER_ACCESS) {
if (data.getData() != null) {
Uri treeUri = data.getData();
tvSAF.setText("Dir: " + data.getData().toString());
currentFolder = treeUri.toString();
saveCurrentFolderToPrefs();
// grantUriPermission(getPackageName(), treeUri,
// Intent.FLAG_GRANT_READ_URI_PERMISSION |
// Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
final int takeFlags = data.getFlags()
& (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
// Check for the freshest data.
getContentResolver().takePersistableUriPermission(treeUri, takeFlags);
}
}
}
}
现在,将保存文件夹保存到共享首选项,而不是每次要保存图像时都要求用户选择文件夹。
您应该使用DocumentFile
课程来保存图片,而不是File
或ParcelFileDescriptor
,有关详细信息,您可以this thread查看是否将图片保存到SD卡{{} 1}}方法和compress(CompressFormat.JPEG, 100, out);
类。
答案 15 :(得分:1)
确保在致电bitmap.compress
之前创建了目录:
new File(FileName.substring(0,FileName.lastIndexOf("/"))).mkdirs();
答案 16 :(得分:1)
嘿,只需将名称命名为 .bmp
这样做:
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
_bitmapScaled.compress(Bitmap.CompressFormat.PNG, 40, bytes);
//you can create a new file name "test.BMP" in sdcard folder.
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "**test.bmp**")
听起来好像只是蠢蠢欲动,但是一旦它被保存在bmp foramt中,就试试吧。欢呼
答案 17 :(得分:0)
实际上不是答案,而是评论。我在Mac上运行模拟器环境,并获得java.io.IOException:权限被拒绝 - 此代码出错:
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
Log.d("DEBUG", "onActivityResult called");
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
if(requestCode == 0 && resultCode == RESULT_OK) {
Log.d("DEBUG", "result is ok");
try{
Bitmap map = (Bitmap) imageReturnedIntent.getExtras().get("data");
File sd = new File(Environment.getExternalStorageDirectory(), "test.png");
sd.mkdirs();
sd.createNewFile();
FileOutputStream out = new FileOutputStream(sd);
map.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
} catch(FileNotFoundException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
我还将manifest-permission android.permission.WRITE_EXTERNAL_STORAGE添加到清单文件中(如其他人所述)。
答案 18 :(得分:0)
无需压缩即可将位图保存到图库中。
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.");
}
}
答案 19 :(得分:-1)
// | == |从位图创建PNG文件:
void devImjFylFnc(String pthAndFylTtlVar, Bitmap iptBmjVar)
{
try
{
FileOutputStream fylBytWrtrVar = new FileOutputStream(pthAndFylTtlVar);
iptBmjVar.compress(Bitmap.CompressFormat.PNG, 100, fylBytWrtrVar);
fylBytWrtrVar.close();
}
catch (Exception errVar) { errVar.printStackTrace(); }
}
// | == |从文件中获取Bimap:
Bitmap getBmjFrmFylFnc(String pthAndFylTtlVar)
{
return BitmapFactory.decodeFile(pthAndFylTtlVar);
}