5

我在实现此代码时遇到问题从 Android 的内部存储器中保存和读取位图/图像

保存和检索我想要的图像,这是我的代码:

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, + name + "profile.jpg");

            FileOutputStream fos = null;
            try {           

                fos = new FileOutputStream(mypath);

           // Use the compress method on the BitMap object to write image to the OutputStream
                myBitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
                fos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

并检索(我不知道我是否做错了)

 @Override
   protected void onResume()
   {
      super.onResume();

      try {
          File f  = new File("imageDir/" + rowID, "profile.jpg");
        Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
        image = (ImageView) findViewById(R.id.imageView2);
        image.setImageBitmap(b);

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

什么都没有发生所以我应该改变什么?

4

4 回答 4

14

要将位图保存在 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;
} 
于 2013-10-19T04:19:57.720 回答
2

我认为 Faibo 的回答应该被接受,因为代码示例是正确的,写得很好,应该可以顺利解决您的具体问题。

如果他的解决方案不能满足您的需求,我想建议一种替代方法。

将图像数据作为 blob 存储在 SQLite DB 中并作为字节数组检索非常简单。编码和解码只需要几行代码(每行),就像一个魅力,而且效率惊人。

我会根据要求提供一个代码示例。

祝你好运!

于 2013-10-19T05:12:34.033 回答
1

请注意,您将选择保存为目录name + profile.jpgimageDir,并且您尝试检索目录profile.jpg下的imageDir/[rowID]检查。

于 2013-10-19T04:14:36.577 回答
0

我让它工作了!

首先确保您的应用已启用存储权限:

转到设备设置>设备>应用程序>应用程序管理器>“您的应用”>权限>启用存储权限!

清单中的权限:

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

所以,如果你想在你的文件存储中创建你自己的目录,你可以使用类似的东西:

FileOutputStream outStream = null;
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();
refreshGallery(outFile);

否则,如果您想在默认设备 DCIM 文件夹中创建一个子目录,然后想在图库中的单独文件夹中查看您的图像:

FileOutputStream fos= null;
    File file = getDisc();
    if(!file.exists() && !file.mkdirs()) {
        //Toast.makeText(this, "Can't create directory to store image", Toast.LENGTH_LONG).show();
        //return;
        print("file not created");
        return;
    }
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyymmsshhmmss");
    String date = simpleDateFormat.format(new Date());
    String name = "FileName"+date+".jpg";
    String file_name = file.getAbsolutePath()+"/"+name;
    File new_file = new File(file_name);
    print("new_file created");
    try {
        fos= new FileOutputStream(new_file);
        Bitmap bitmap = viewToBitmap(iv, iv.getWidth(), iv.getHeight() );
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        Toast.makeText(this, "Save success", Toast.LENGTH_LONG).show();
        fos.flush();
        fos.close();
    } catch (FileNotFoundException e) {
        print("FNF");
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    refreshGallery(new_file);

辅助功能:

public void refreshGallery(File file){
    Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    intent.setData(Uri.fromFile(file));
    sendBroadcast(intent);
}

private File getDisc(){
    String t= getCurrentDateAndTime();
    File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
    return new File(file, "ImageDemo");
}

private String getCurrentDateAndTime() {
    Calendar c = Calendar.getInstance();
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
    String formattedDate = df.format(c.getTime());
    return formattedDate;

public static Bitmap viewToBitmap(View view, int width, int height) {
    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    view.draw(canvas);
    return bitmap;
}

希望这可以帮助!

于 2016-08-11T19:10:41.360 回答