繁体   English   中英

如何从字节数组创建文件并将其添加到android中的画廊

[英]How to create a File from byte array and add it to the gallery in android

我有一个功能:

    public void onPictureTaken(byte[] data, Camera camera) {

    //Creating the Image file here
    }



 public static void addImageToGallery(final String filePath, final Context context) {

        ContentValues values = new ContentValues();

        values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
        values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
        values.put(MediaStore.MediaColumns.DATA, filePath);

        context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
    }

  1. 如何从data正确创建文件。
  2. 我想创建一个文件并获取文件的绝对路径
  3. 最后,我想将图像添加到图库中,对此我已经具有

尝试这样的事情。

private void createFile(byte[] fileData) {
            try {
                //Create directory..
                File root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES + "/YOUR_FOLDER_NAME");
                File dir = new File(root + File.separator);
                if (!dir.exists()) dir.mkdir();

                //Create file..
                File file = new File(root + File.separator + "YOUR_IMAGE_NAME");
                file.createNewFile();

                FileOutputStream out = new FileOutputStream(file);
                out.write(fileData);
                out.close();

            }
            catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }

从字节数组创建文件:

FileOutputStream fos = new FileOutputStream("pathname");
fos.write(myByteArray);
fos.close();

或使用Apache Commons IO主页 ):

FileUtils.writeByteArrayToFile(new File("pathname"), myByteArray)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM