安卓如何将图片保存到内部存储中

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

“什么都没有发生,我应该改变什么?”

2
请在问题中附上您的Logcat。 - Salman Khakwani
4个回答

14

要将位图保存在SD卡中,请使用以下代码:

存储图片

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

如何从另一个类中检索(位图)以便设置它:image =(ImageView)findViewById(R.id.imageView2); image.setImageBitmap(...); - user2580401
此答案中的代码已直接从Android开发者网站复制粘贴而来,您可以在该网站找到更多有用的答案。 - Masterfool
3
关于内部存储的问题,您所提供的答案并不正确。您提供的是关于外部存储的回答。请重新检查并提供正确的答案。 - Ranjithkumar

2

我认为应该接受Faibo的答案,因为代码示例是正确的、写得很好,而且应该可以解决你特定的问题,毫不费力。

如果他的解决方案不符合您的需求,我想提出一种替代方法。

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

如有需要,我可以提供一个代码示例。

祝你好运!


但是,如果我想添加近5000张图片,会有任何问题吗? - user2580401
如果您能提供一个例子,我将不胜感激。 - Coderji
小例子(位图<->字节数组): public Bitmap setImageFromByteArray(byte[] byImage){ ByteArrayInputStream in = new ByteArrayInputStream(byImage); return BitmapFactory.decodeStream(in); }public byte[] getByteArrayFromImage(Bitmap image){ ByteArrayOutputStream out = new ByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.JPEG, 80, out); return out.toByteArray(); } - v1k

1
请注意,您正在将选项保存为 name + profile.jpg imageDir 目录下,并尝试在 imageDir / [rowID] 目录下检索为 profile.jpg 。请检查。

名称和行ID包含相同的值,这只是因为它们在不同的类中,但还是谢谢。 - user2580401

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

希望这能有所帮助!

3
你是否给出了正确的答案?问题是关于内部存储的,询问如何将图片保存到安卓的内部存储中,而你的答案是关于外部存储的。请修正答案。 - Ranjithkumar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接