2017-08-26 66 views
1

添加到庫中我有一個函數::如何創建字節數組文件,它在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. 的絕對路徑,最後,我想給圖像添加到庫中,我已經具備的功能
+0

看到'MediaStore.Images.Media#insertImage()' – pskink

+0

你看到它的javadoc:「插入圖像,併爲它創建一個縮略圖。返回新創建的圖像的URL,如果圖像因任何原因未能存儲,則返回null。「? – pskink

+0

如何創建縮略圖? – Devrath

回答

1

嘗試是這樣的..

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

創建從字節數組的文件:

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

,或者使用Apache Commons IOhome):

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

Upvoted ... for suggest Apache Commons IO :) – Devrath