507

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

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

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

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

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

4

19 回答 19

970
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();
}
于 2009-03-23T11:22:56.550 回答
144

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

下面是一个通过它获得的 Bitmap 实例的示例getImageBitmap(myurl),可以将其压缩为 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());
于 2010-06-10T10:42:30.660 回答
38
outStream = new FileOutputStream(file);

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

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
于 2011-10-14T22:57:43.923 回答
28

内部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();
}
于 2012-01-25T16:19:22.717 回答
13

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

于 2009-12-09T13:53:48.770 回答
10

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

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

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

于 2016-04-02T09:41:55.620 回答
8

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

于 2009-03-16T04:10:15.603 回答
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) {

}
于 2011-06-22T09:25:25.767 回答
7

我知道这个问题很老,但现在我们可以在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
        )
    }

也不要忘记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>
于 2020-10-28T19:14:02.933 回答
6

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

我是这样设计的:

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

 }
于 2010-11-18T09:26:48.643 回答
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")));
于 2015-04-08T09:52:47.620 回答
3

您想将位图保存到您选择的目录中。我制作了一个 ImageWorker 库,使用户能够加载、保存和转换位图/drawables/base64 图像。

最小 SDK - 14

先决条件

  • 保存文件需要 WRITE_EXTERNAL_STORAGE 权限。
  • 检索文件需要 READ_EXTERNAL_STORAGE 权限。

保存位图/Drawable/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' }
        }
    }

在应用程序级别 Gradle

dependencies {
            implementation 'com.github.ihimanshurawat:ImageWorker:0.51'
    }

您可以在https://github.com/ihimanshurawat/ImageWorker/blob/master/README.md上阅读更多内容

于 2018-12-09T04:44:19.557 回答
2

确保在调用之前创建目录bitmap.compress

new File(FileName.substring(0,FileName.lastIndexOf("/"))).mkdirs();
于 2016-02-18T19:21:39.040 回答
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;
} 
于 2018-06-28T13:17:34.153 回答
2

一些新设备不保存位图所以我解释了一点..

确保您已在权限下方添加

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

xml并在文件夹名称provider_paths.xml下创建一个 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);
    }
于 2019-01-14T06:09:33.933 回答
2

将位图保存到您的画廊而不压缩。

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.");
    }
}
于 2019-07-13T04:48:28.743 回答
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 中就可以尝试一下……干杯

于 2013-01-22T11:47:39.097 回答
1

在 Android 4.4 Kitkat 之后,截至 2017 年,Android 4.4 及以下的份额约为 20% 并且正在下降,无法使用File类和getExternalStorageDirectory()方法保存到 SD 卡。此方法返回您的设备内存和图像保存对每个应用程序可见。您还可以仅将图像保存为您的应用程序私有,并在用户使用方法删除您的应用程序时被删除openFileOutput()

从 Android 6.0 开始,您可以将 SD 卡格式化为内部存储器,但仅限于您的设备。(如果您将 SD 汽车格式化为内部存储器,则只有您的设备可以访问或查看其内容)您可以使用以下方式保存到该 SD 卡其他答案,但如果您想使用可移动 SD 卡,您应该阅读下面的答案。

您应该使用存储访问框架获取 uri 到onActivityResult活动的文件夹方法以获取用户选择的文件夹,并添加可检索持久权限以便在用户重新启动设备后能够访问文件夹。

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

            }
        }
    }
}

现在,将保存文件夹保存到共享首选项,不要在每次要保存图像时要求用户选择文件夹。

您应该使用DocumentFileclass 来保存您的图像,而不是FileParcelFileDescriptor有关更多信息,您可以查看此线程compress(CompressFormat.JPEG, 100, out);以使用方法和DocumentFile类将图像保存到 SD 卡。

于 2017-09-15T11:42:12.823 回答
-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);
}
于 2017-06-29T19:22:48.573 回答