在 Android 中从内存中保存和读取位图/图像 [英] Saving and Reading Bitmaps/Images from Internal memory in Android

查看:28
本文介绍了在 Android 中从内存中保存和读取位图/图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的是将图像保存到手机的内存中(不是 SD 卡).

What I want to do, is to save an image to the internal memory of the phone (Not The SD Card).

我该怎么做?

我已将图像直接从相机获取到我的应用程序中的图像视图,一切正常.

I have got the image directly from the camera to the image view in my app its all working fine.

现在我想要的是将此图像从 Image View 保存到我的 android 设备的内存中,并在需要时访问它.

Now what I want is to save this image from Image View to the Internal memory of my android device and also access it when required.

谁能指导我如何做到这一点?

Can anyone please guide me how to do this?

我对android有点陌生,所以如果我能有详细的程序,我将不胜感激.

I am a little new to android so please, I would appreciate if I can have a detailed procedure.

推荐答案

使用下面的代码将图片保存到内部目录.

Use the below code to save the image to internal directory.

private String saveToInternalStorage(Bitmap bitmapImage){
        ContextWrapper cw = new ContextWrapper(getApplicationContext());
         // path to /data/data/yourapp/app_data/imageDir
        File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
        // Create imageDir
        File mypath=new File(directory,"profile.jpg");

        FileOutputStream fos = null;
        try {           
            fos = new FileOutputStream(mypath);
       // Use the compress method on the BitMap object to write image to the OutputStream
            bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
        } catch (Exception e) {
              e.printStackTrace();
        } finally {
            try {
              fos.close();
            } catch (IOException e) {
              e.printStackTrace();
            }
        } 
        return directory.getAbsolutePath();
    }

说明:

1.目录将使用给定的名称创建.Javadocs 用于说明它将在何处创建目录.

1.The Directory will be created with the given name. Javadocs is for to tell where exactly it will create the directory.

2.您必须提供要保存的图像名称.

2.You will have to give the image name by which you want to save it.

从内存中读取文件.使用下面的代码

To Read the file from internal memory. Use below code

private void loadImageFromStorage(String path)
{

    try {
        File f=new File(path, "profile.jpg");
        Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
            ImageView img=(ImageView)findViewById(R.id.imgPicker);
        img.setImageBitmap(b);
    } 
    catch (FileNotFoundException e) 
    {
        e.printStackTrace();
    }

}

这篇关于在 Android 中从内存中保存和读取位图/图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆