【问题标题】:File saving outputstream on androidandroid上的文件保存输出流
【发布时间】:2014-10-22 03:34:03
【问题描述】:

我正在制作一个可以拍照的安卓应用。我写了一些代码来保存应用程序拍摄的照片。我要保存文件的目录在内部存储和名为 DCIM 的文件夹中。但是,每次我尝试保存照片时,应用程序都会崩溃。以下是我的代码:

FileOutputStream outStream = null;
                     try {
                         outStream = new FileOutputStream(String.format(
                                 "sdcard/DCIM/jgjk.jpg", System.currentTimeMillis()));
                         outStream.write(data);
                         outStream.close();
                         Log.d("Log", "onPictureTaken - wrote bytes: " + data.length);
                     } catch (FileNotFoundException e) {
                         e.printStackTrace();
                     } catch (IOException e) {
                         e.printStackTrace();
                     } finally {
                     }

代码有什么问题吗?

【问题讨论】:

  • 你看过异常的LogCat了吗?
  • 你打算用 String.format("sdcard/DCIM/jgjk.jpg", System.currentTimeMillis()) 做什么?这似乎是错误的。
  • 迈克尔:是的,这似乎是错误的。我在这里寻找建议。
  • 如帕尼尼所说,请附上您的日志猫,但有例外

标签: android android-camera storage


【解决方案1】:

这样就可以了

在onActivityResult中获取位图

public void onActivityResult(int requestCode, int resultCode, Intent data) 
    {
         if(requestCode==PIC_CROP)
        {
             if(resultCode==RESULT_OK)
             {
             Bundle extras = data.getExtras();
                if (extras != null) {               
                    Bitmap bmp = extras.getParcelable("data");
                    savePhoto(bmp);
                }
             }
        }

}


public void savePhoto(Bitmap bmp)
        {
        dir = Environment.getExternalStorageDirectory().toString() + "/DCIM/"; 
        File newdir = new File(dir); 
        newdir.mkdirs();
        FileOutputStream out = null;

        //file name
        Calendar c = Calendar.getInstance();
        String date = fromInt(c.get(Calendar.MONTH))
                    + fromInt(c.get(Calendar.DAY_OF_MONTH))
                    + fromInt(c.get(Calendar.YEAR))
                    + fromInt(c.get(Calendar.HOUR_OF_DAY))
                    + fromInt(c.get(Calendar.MINUTE))
                    + fromInt(c.get(Calendar.SECOND));
        File imageFileName = new File(newdir, "crop_"+date.toString() + ".jpg");

        try
        {
         out = new FileOutputStream(imageFileName);
         bmp.compress(Bitmap.CompressFormat.JPEG, 100, out);
         out.flush();
         out.close();
         out = null;
        } catch (Exception e)
        {
        e.printStackTrace();
        }
        }


public String fromInt(int val)
{
return String.valueOf(val);
}

【讨论】:

  • 谢谢拉詹。感谢您的帮助。
  • 是的,欢迎......如果您发现有用的赞成票,那么其他人可能会受益。
  • 我目前的声誉不允许我对任何帖子或评论进行投票。
  • rajan : 我应该用什么类型初始化对象目录?
  • 和 Eclipse 显示无法为数组类型字节调用 getExtras。
猜你喜欢
  • 2020-11-12
  • 2015-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-10
  • 1970-01-01
  • 2011-06-10
  • 2021-10-31
相关资源
最近更新 更多