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

Java 如何从字节数组创建文件并将其添加到android中的库中,java,android,file,Java,Android,File,我有一个函数:: 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

我有一个函数::

    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);
    }

  • 如何正确地从
    数据创建文件
  • 我想创建一个文件并获取文件的绝对路径
  • 最后,我想将图像添加到gallery中,我已经有了这个功能

  • 试试这样的

    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();
    
    或使用():


    请参阅
    MediaStore.Images.Media#insertImage()
    您是否看到其javadocs:“插入图像并为其创建缩略图。返回新创建图像的URL,如果由于任何原因无法存储图像,则返回null。”?如何创建缩略图?使用
    MediaStore.Images.Media#insertImage()
    FileUtils.writeByteArrayToFile(new File("pathname"), myByteArray)