【问题标题】:Android create file from drawableAndroid从drawable创建文件
【发布时间】:2015-08-25 09:15:49
【问题描述】:

有没有办法从可绘制的图像创建文件以通过MultypartEntity 发送它?我总是出错。

fileUri =  Uri.parse("android.resource://com.wellbread/drawable/placeholder_avatar.png");
mCurrentPhotoPath = fileUri.toString();


 java.io.FileNotFoundException: android.resource:/com.wellbread/drawable/placeholder_avatar.png: open failed: ENOENT (No such file or directory)
08-25 12:01:53.134    3663-3684/? W/System.err﹕ at libcore.io.IoBridge.open(IoBridge.java:456)

【问题讨论】:

  • 1- 将可绘制图像复制到 sdcard 中,然后创建进一步的步骤。
  • 你看我的回答了吗?
  • 是的,太好了!它可以工作,但实际上没有创建文件,所以如果有任何方法可以从我不知道的字节 [] 创建文件,那就太好了
  • 如果您已经有字节数组,则无需创建 File 对象,您可以在我的回答中使用 addBinaryBody(...) 的实现来发布字节数组。位图数据是字节数组。

标签: android file


【解决方案1】:

试试下面的示例代码:

        Drawable drawable = getResources().getDrawable(R.drawable.ic_action_home);
        if (drawable != null) {
            Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
            final byte[] bitmapdata = stream.toByteArray();
            String url = "http://10.0.2.2/api/fileupload";
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

            // Add binary body
            if (bitmapdata != null) {
                ContentType contentType = ContentType.create("image/png");
                String fileName = "ic_action_home.png";
                builder.addBinaryBody("file", bitmapdata, contentType, fileName);
                httpEntity = builder.build();
                ...
            }
        ...
        }

【讨论】:

    【解决方案2】:

    试试这个:

    try
            {
            File f=new File("file name");
           InputStream inputStream = getResources().openRawResource(id); // id drawable
            OutputStream out=new FileOutputStream(f);
            byte buf[]=new byte[1024];
            int len;
            while((len=inputStream.read(buf))>0)
            out.write(buf,0,len);
            out.close();
            inputStream.close();
            }
            catch (IOException e){}
            } 
    

    【讨论】:

    • 那么“文件名”是什么?我实际上正在寻找文件。你说它必须在原始文件夹中?
    • 在你的回答中我需要把一个字符串路径放到文件中,但问题是我的新文件一直说找不到它。
    • Это имя и путь файла куда он сохранится из 可绘制
    【解决方案3】:

    您可以使用以下代码从可绘制资源中打开 InputStream:

         try 
            { 
            File f=new File("your file name");
    //id is some like R.drawable.b_image
            InputStream inputStream = getResources().openRawResource(id);
            OutputStream out=new FileOutputStream(f);
            byte buf[]=new byte[1024];
            int len;
            while((len=inputStream.read(buf))>0)
            out.write(buf,0,len);
            out.close();
            inputStream.close();
            } 
            catch (IOException e){}
            } 
    

    【讨论】:

    • 文件名用什么?
    • 在你的回答中我需要把一个字符串路径放到文件中,但问题是我的新文件一直说找不到它。
    • 文件名可以是这样的 ==> File f = new File(Environment.getExternalStorageDirectory() .getAbsolutePath() + File.separator + fileName);并且文件名可能类似于 temp.png
    【解决方案4】:

    你必须从drawable中获取Bitmap:

    public static Bitmap decodeAndSetWidthHeight(Resources res, int resId, int reqWidth, int reqHeight){
            Bitmap btm = BitmapHelper.decodeSampledBitmapFromResource(res, resId, reqWidth, reqHeight);
            return decodeAndSetWidthHeight(btm, reqWidth, reqHeight);
        }
    

    然后你可以从位图创建文件

        public static File bitmapToFile(Bitmap bitmap){
            File outFile = FileHelper.getImageFilePNG();
            FileOutputStream out = null;
            try {
                out = new FileOutputStream(outFile);
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (out != null) {
                        out.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    
            return outFile;
        }
    

    UPDATE(抱歉,忘记提供一些方法):

    public static File getImageFilePNG() {
        File sdCard = Environment.getExternalStorageDirectory();
        File dir = new File(sdCard.getAbsolutePath() + "/any name folder");
        dir.mkdirs();
    
        String fileName = String.format("%d.png", System.currentTimeMillis());
        return new File(dir, fileName);
    }
    
    
     public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
                                                         int reqWidth, int reqHeight) {
    
        // First decode with inJustDecodeBounds=true to check dimensions
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(res, resId, options);
    
        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
        Log.d("ANT", "options.inSampleSize : " + options.inSampleSize);
    
        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeResource(res, resId, options);
    }
    
     public static Bitmap decodeAndSetWidthHeight(Bitmap btm, int reqWidth, int reqHeight){
        Matrix m = new Matrix();
        RectF inRect = new RectF(0, 0, btm.getWidth(), btm.getHeight());
        RectF outRect = new RectF(0, 0, reqWidth, reqHeight);
        m.setRectToRect(inRect, outRect, Matrix.ScaleToFit.FILL);
        float[] values = new float[9];
        m.getValues(values);
    
        return Bitmap.createScaledBitmap(btm, (int) (btm.getWidth() * values[0]), (int) (btm.getHeight() * values[4]), true);
    }
    

    【讨论】:

    • 您能告诉创建文件的文件名使用什么吗?也许是一些完整的路径?
    • 在你的回答中我需要把一个字符串路径放到文件中,但问题是我的新文件一直说找不到它。
    猜你喜欢
    • 1970-01-01
    • 2011-08-19
    • 2016-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多