将ImageView中的图像保存到内部存储

时间:2016-08-08 02:54:18

标签: android android-studio bitmap android-imageview internal-storage

我创建了一个ImageView,我可以看到Camera的预览并将捕获的图像加载到ImageView中,我想将图像存储到内部存储器的目录中。我已经推荐了许多帖子并试过但我无法在内存中找到我的图像。这是我用过的代码:

 package com.example.shravan.camera;

 import android.content.Context;
 import android.content.ContextWrapper;
 import android.content.Intent;
 import android.content.pm.PackageManager;
 import android.graphics.Bitmap;
 import android.graphics.drawable.BitmapDrawable;
 import android.net.Uri;
 import android.os.Bundle;
 import android.provider.MediaStore;
 import android.support.v7.app.AppCompatActivity;
 import android.util.Log;
 import android.view.View;
 import android.widget.Button;
 import android.widget.ImageView;

 import java.io.File;
 import java.io.FileOutputStream;
 import java.io.IOException;


 public class MainActivity extends AppCompatActivity {
  private final String TAG = "abc";


static final int REQUEST_IMAGE_CAPTURE =1 ;
ImageView iv;
Uri imageUri;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button btn = (Button)findViewById(R.id.myB);
    iv = (ImageView) findViewById(R.id.myIV);
    //disable the button if the user has no camera
    if(!hasCamera())
    {
        btn.setEnabled(false);
    }
}


public boolean hasCamera()
{

    return getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY);
}

//on click event handler that launches the camera
public void launchCamera(View v)
{
    Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(i, REQUEST_IMAGE_CAPTURE);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK)
    {
        imageUri=data.getData();
        iv.setImageURI(imageUri);;
    }
}

public void SaveFile(View v){
    BitmapDrawable drawable = (BitmapDrawable) iv.getDrawable();
    Bitmap bitmap = drawable.getBitmap();

    print("Creating cw");
    ContextWrapper cw = new ContextWrapper(this.getApplicationContext());
    print("Creating dir");
    File directory = cw.getDir("ImagesDir", Context.MODE_PRIVATE);
    print("Created dir" + directory);
    File mypath=new File(directory,"myImagesDGS.jpg");
    print("path is"+mypath);

    FileOutputStream fos = null;
    try {
        print("creating fos");
        fos = new FileOutputStream(mypath);
        print("Compressing bitmap");
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            fos.close();
            print("fos closed");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

private void print(String str){
    Log.d(TAG, str);
}

}

我已经制作了许多日志消息进行调试,我找到了一条在手机中无法找到的路径。这是logcat:

  

08-07 21:47:37.089 11030-11030 / com.example.shravan.camera D / abc:       创建cw 08-07

     

21:47:37.089 11030-11030 / com.example.shravan.camera       D / abc:创建目录08-07

     

21:47:37.099       11030-11030 / com.example.shravan.camera D / abc:已创建       dir / data / user / 0 / com.example.shravan.camera / app_ImagesDir 08-07

     

21:47:37.099 11030-11030 / com.example.shravan.camera D / abc:path       是/数据/用户/ 0 / com.example.shravan.camera / app_ImagesDir / myImagesDGS.jpg

     

08-07 21:47:37.099 11030-11030 / com.example.shravan.camera D / abc:       创造fos

     

08-07 21:47:37.099 11030-11030 / com.example.shravan.camera       D / abc:压缩位图

     

08-07 21:47:42.589       11030-11030 / com.example.shravan.camera D / abc:fos已关闭

我需要检查一下,我应该改变吗?请帮忙!

7 个答案:

答案 0 :(得分:4)

搞定了!

我使用此代码在文件存储中创建目录,然后存储图像:

FileOutputStream outStream = null;

    // Write to SD Card
    try {
        File sdCard = Environment.getExternalStorageDirectory();
        File dir = new File(sdCard.getAbsolutePath() + "/camtest");
        dir.mkdirs();

        String fileName = String.format("%d.jpg", System.currentTimeMillis());
        File outFile = new File(dir, fileName);

        outStream = new FileOutputStream(outFile);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
        outStream.flush();
        outStream.close();

        Log.d(TAG, "onPictureTaken - wrote to " + outFile.getAbsolutePath());

        refreshGallery(outFile);
    } catch (FileNotFoundException e) {
        print("FNF");
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
    }

我的权限:

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

最后,最重要的是:

转到设备设置&gt;设备&gt;应用程序&gt;应用程序管理器&gt;&#34;您的应用&#34;&gt;权限&gt;启用存储权限!

答案 1 :(得分:0)

您的图片正在保存此路径/data/user/0/com.example.shravan.camera/app_ImagesDir/myImagesDGS.jpg 但你不是access.try这个代码用于iamge阅读。将此方法调用到onCreate这个方法返回你的位图。

 Bitmap mBitmap= getImageBitmap(this,"myImagesDGS","jpg");

   if(mBitmap !=null){

yourImageView.setBitmap(mBitmap);

}else{

Log.d("MainActivity","Image is not found");
}

是sepread方法

     public Bitmap getImageBitmap(Context context,String name,String extension){
        name=name+"."+extension;  
        try{ 
            FileInputStream fis = context.openFileInput(name);
                Bitmap b = BitmapFactory.decodeStream(fis);
                fis.close();
                return b;
            } 
            catch(Exception e){
            } 
            return null; 
        }

答案 2 :(得分:0)

试试这个。我修改了我的代码以适合您提供的代码。我没有测试它。我将拍摄的照片临时存储到带有时间戳的文件中,然后使用文件名来检索文件。希望它有所帮助

   _textView.textContainerInset = UIEdgeInsetsZero;
   _textView.textContainer.lineFragmentPadding = 0;

答案 3 :(得分:0)

使用该代码,您将结束将文件存储到私人应用程序数据。 除了没有root权限的应用程序本身之外,您无法使用其他应用程序访问该数据。如果您希望其他应用程序可以访问您的图像文件,则可以在声明文件路径时使用此代码来获取公共映像目录。

File albumF;
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
    albumF = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
} else {
    albumF = context.getFilesDir();
}

如果您需要在子公共图库目录中创建子目录,可以像这样更改上面的代码:

File albumF;
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
    albumF = new File(Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_DCIM), YOUR_SUB_DIRECTORY_STRING);
} else {
    albumF = new File(context.getFilesDir(), YOUR_SUB_DIRECTORY_STRING);
}

您可能需要添加此代码才能创建该专辑目录

if (!albumF.exists()) {
    albumF.mkdirs();
}

答案 4 :(得分:0)

当前图片保存的位置无法被其他应用程序访问。最好将它们保存在可访问的位置。就像这样..

BitmapDrawable drawable = (BitmapDrawable) iv.getDrawable();
Bitmap bitmap = drawable.getBitmap();
 try {
           String root = Environment.getExternalStorageDirectory().toString();
           File file = new File(root + "/YourDirectory/myImagesDGS.jpg");
           FileOutputStream out = new FileOutputStream(file);
           bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
           out.flush();
           out.close();

                                } catch (Exception ex) {
                                    ex.printStackTrace();
                                }

然后你可以像这样检索你保存的图像..

String root = Environment.getExternalStorageDirectory().toString();
  File file = new File(root + "/YourDirectory/myImagesDGS.jpg");    
Bitmap bmap=BitmapFactory.decodeFile(file.getAbsolutePath());

答案 5 :(得分:0)

尝试使用ImageSaver。它是从内部和外部存储保存和加载图像的同步方式。

用法

  • 保存:

    new ImageSaver(context).
            setFileName("myImage.png").
            setDirectoryName("images").
            setExternal(true).
            save(bitmap);
    
  • 加载:

    Bitmap bitmap = new ImageSaver(context).
            setFileName("myImage.png").
            setDirectoryName("images").
            setExternal(true).
            load();
    

答案 6 :(得分:0)

@Shravan DG 提出的解决方案给我带来了错误。我对他的代码做了一点修改,并且没有错误。

 private void downloadQR()
{
    FileOutputStream outStream = null;
    
    try {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "QRCode_" + timeStamp + ".jpg";
        File storageDir = new File(Environment.getExternalStorageDirectory().toString(), "PARENT_DIR)/CHILD_DIR/");
        storageDir.mkdirs();

        File outFile = new File(storageDir, imageFileName);
        outStream = new FileOutputStream(outFile);
        BitmapDrawable drawable = (BitmapDrawable) qrCode.getDrawable();
        Bitmap bitmap = drawable.getBitmap();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
        outStream.flush();
        outStream.close();

        Log.d(TAG, "onPictureTaken - wrote to " + outFile.getAbsolutePath());

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {

    }
}

冷静丸:)