【问题标题】:bitmap to file that can be uploaded via async位图到可以通过异步上传的文件
【发布时间】:2013-09-03 21:49:44
【问题描述】:

由于之前在实施有效的照片上传系统时遇到的问题而头疼了一天,我觉得自己快要完成了。我的最后一步也是最后一步是允许我的用户在图像被裁剪后上传图像。

进行裁剪后,我可以访问位图和使用该位图的 imageView。我使用的异步请求库是:http://loopj.com/android-async-http/

我使用的 api 是这样设置的,我需要像这样发送一个“文件”:

File myFile = new File("/path/to/file.png");
RequestParams params = new RequestParams();
try {
    params.put("profile_picture", myFile);
} catch(FileNotFoundException e) {}

将位图转换为“文件”的选项有哪些

【问题讨论】:

    标签: android file asynchronous upload bitmap


    【解决方案1】:

    您可以使用Bitmap.compress 方法将位图保存到文件中。只需提供适当的 FileOutputStream 作为参数即可。

    您也可以不使用文件上传图片,只需将其保存到字节数组,然后作为该数组上传。

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 85, out);
    byte[] myByteArray = out.toByteArray();
    RequestParams params = new RequestParams();
    params.put("profile_picture", new ByteArrayInputStream(myByteArray), "image.png");
    

    【讨论】:

    • 仅供参考:PNG 是一种无损格式,这意味着 85 将被忽略。
    【解决方案2】:

    试试这个:

    String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() + 
                            "/to";
    File dir = new File(file_path);
    if(!dir.exists)
    dir.mkdirs();
    File file = new File(dir, "file.png");
    FileOutputStream fOut = new FileOutputStream(file);
    
    bmp.compress(Bitmap.CompressFormat.PNG, 85, fOut);
    fOut.flush();
    fOut.close();
    

    并将以下权限放入您的清单文件中。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-17
      • 1970-01-01
      • 1970-01-01
      • 2011-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多