Android 将位图保存到位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/649154/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 02:22:10  来源:igfitidea点击:

Save bitmap to location

androidbitmapsave

提问by Chrispix

I am working on a function to download an image from a web server, display it on the screen, and if the user wishes to keep the image, save it on the SD card in a certain folder. Is there an easy way to take a bitmap and just save it to the SD card in a folder of my choice?

我正在开发一个功能,从网络服务器下载图像,将其显示在屏幕上,如果用户希望保留图像,请将其保存在 SD 卡上的某个文件夹中。有没有一种简单的方法来获取位图并将其保存到我选择的文件夹中的 SD 卡中?

My issue is that I can download the image, display it on screen as a Bitmap. The only way I have been able to find to save an image to a particular folder is to use FileOutputStream, but that requires a byte array. I am not sure how to convert (if this is even the right way) from Bitmap to byte array, so I can use a FileOutputStream to write the data.

我的问题是我可以下载图像,将其作为位图显示在屏幕上。我能够找到将图像保存到特定文件夹的唯一方法是使用 FileOutputStream,但这需要一个字节数组。我不确定如何将(如果这甚至是正确的方式)从 Bitmap 转换为字节数组,因此我可以使用 FileOutputStream 来写入数据。

The other option I have is to use MediaStore :

我的另一个选择是使用 MediaStore :

MediaStore.Images.Media.insertImage(getContentResolver(), bm,
    barcodeNumber + ".jpg Card Image", barcodeNumber + ".jpg Card Image");

Which works fine to save to SD card, but does not allow you to customize the folder.

这可以很好地保存到 SD 卡,但不允许您自定义文件夹。

回答by Ulrich Scheller

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

回答by JoaquinG

You should use the Bitmap.compress()method to save a Bitmap as a file. It will compress (if the format used allows it) your picture and push it into an OutputStream.

您应该使用该Bitmap.compress()方法将位图保存为文件。它将压缩(如果使用的格式允许)您的图片并将其推送到 OutputStream。

Here is an example of a Bitmap instance obtained through getImageBitmap(myurl)that can be compressed as a JPEG with a compression rate of 85% :

下面是一个通过getImageBitmap(myurl)它获得的 Bitmap 实例的例子,它可以压缩为 JPEG,压缩率为 85% :

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

回答by user996042

outStream = new FileOutputStream(file);

will throw exception without permission in AndroidManifest.xml (at least in os2.2):

将在 AndroidManifest.xml 中未经许可抛出异常(至少在 os2.2 中):

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

回答by Alessandro

Inside onActivityResult:

内部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();
}

回答by shinydev

Some formats, like PNG which is lossless, will ignore the quality setting.

某些格式,例如无损的 PNG,将忽略质量设置。

回答by A-Droid Tech

Here is the sample code for saving bitmap to file :

这是将位图保存到文件的示例代码:

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

Now call this function to save the bitmap to internal memory.

现在调用此函数将位图保存到内部存储器。

File newfile = savebitmap(bitmap);

File newfile = savebitmap(bitmap);

I hope it will help you. Happy codeing life.

我希望它会帮助你。快乐的编码生活。

回答by Ashish Anand

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

}

回答by TofuBeer

Why not call the Bitmap.compressmethod with 100 (which sounds like it is lossless)?

为什么不Bitmap.compress使用 100调用该方法(听起来像是无损的)?

回答by user511895

I would also like to save a picture. But my problem(?) is that I want to save it from a bitmap that ive drawed.

我也想保存图片。但是我的问题(?)是我想从我绘制的位图中保存它。

I made it like this:

我是这样制作的:

 @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();
            }

 }

回答by JulienGenoud

The way I found to send PNG and transparency.

我发现发送 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")));