【问题标题】:how to convert an image intent into a file type in android如何在android中将图像意图转换为文件类型
【发布时间】:2023-03-07 19:02:01
【问题描述】:

我正在开发一个需要将图像转换为文件的应用程序。以下是我尝试实现它的方法:-

protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    super.onActivityResult(requestCode, resultCode, data);

    if(resultCode==RESULT_OK)   
    {
        if(requestCode==CAMERA_REQUEST)
        {
            File camImage= (File) data.getExtras().get("data"); 
        }
    }
}

没有错误,但是每当我拍照并按确定按钮时,它就会崩溃。有没有办法将“数据”转换为文件。 TIA

【问题讨论】:

    标签: android android-intent android-image android-file


    【解决方案1】:

    额外的dataBitmap。您可以调用compress() on the Bitmap 将其写入文件(通过OutputStream)。请在后台线程上执行此工作。

    【讨论】:

      【解决方案2】:

      希望对你有帮助:

      //create a file to write bitmap data
      File f = new File(context.getCacheDir(), "filename");
      f.createNewFile();
      
      //Convert bitmap to byte array
      Bitmap bitmap = your bitmap;
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      bitmap.compress(CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
      byte[] bitmapdata = bos.toByteArray();
      
      //write the bytes in file
      FileOutputStream fos = new FileOutputStream(f);
      fos.write(bitmapdata);
      fos.flush();
      fos.close();
      

      在文件名中,您可以将路径设置为 sdcard 目录。

      【讨论】:

        【解决方案3】:

        试试这个..

        protected void onActivityResult(int requestCode, int resultCode, Intent data)
            {
                super.onActivityResult(requestCode, resultCode, data);
        
                if(resultCode==RESULT_OK)   
                {
                    if(requestCode==CAMERA_REQUEST)
                    {
                        String path= (String) data.getExtras().get("data"); 
                        File file = new File(path);
                    }
                }
            }
        

        【讨论】:

          猜你喜欢
          • 2020-12-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-09-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-30
          • 1970-01-01
          相关资源
          最近更新 更多