2017-01-23 53 views
-1

我想将位图对象转换为文件对象。 但是,我想将文件对象存储在内存中,而不是存储在SD卡或内部存储器中,以便我可以在不保存在库中的情况下使用图像文件。android,如何将位图转换为文件对象

下面的代码只是为了获取位图,并将其转换成更小的图像

public void onActivityResult(int requestCode, int resultCode, Intent data){ 
    super.onActivityResult(requestCode, resultCode, data); 

    if(resultCode != RESULT_OK) 
     return; 

    if(requestCode == PICK_FROM_CAMERA){ 

     imageUri = data.getData(); 



     Cursor c = this.getContentResolver().query(imageUri, null, null, null, null); 
     c.moveToNext(); 
     absolutePath = c.getString(c.getColumnIndex(MediaStore.MediaColumns.DATA)); 

     Glide.with(this).load(imageUri).into(image); 


     BitmapFactory.Options options = new BitmapFactory.Options(); 
     options.inSampleSize = 4; 
     bitmap = BitmapFactory.decodeFile(absolutePath, options); 



    } 
+0

'不SD卡或内部存储,以便我可以使用图像文件。不可能。没有其他地方的文件。 – greenapps

+0

好的问题太难了。 – greenapps

回答

3

希望这将帮助你

private static void persistImage(Bitmap bitmap, String name) { 
File filesDir = getAppContext().getFilesDir(); 
File imageFile = new File(filesDir, name + ".jpg"); 

OutputStream os; 
try { 
    os = new FileOutputStream(imageFile); 
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os); 
    os.flush(); 
    os.close(); 
} catch (Exception e) { 
    Log.e(getClass().getSimpleName(), "Error writing bitmap", e); 
    } 
} 
+0

谢谢!!!!!!!!! –

+0

如果它的帮助然后upvote它 – Akash

+1

@谢谢!!!!!!!!!'?????你怎么能这么大声批准这个解决方案?你说'不在SD卡或内部存储器中, – greenapps

0

希望这有助于

//create a file to write bitmap data 
File f = new File(context.getCacheDir(), filename); 
f.createNewFile(); 

//Convert bitmap to byte array 
Bitmap bitmap = your bitmap; 
ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
bitmap.compress(CompressFormat.PNG, 0 /*ignored for PNG*/, bos); 
byte[] bitmapdata = bos.toByteArray(); 

//write the bytes in file 
FileOutputStream fos = new FileOutputStream(f); 
fos.write(bitmapdata); 
fos.flush(); 
fos.close(); 
+0

您最好删除前三行。最后五个。之后,你有完美的答案。 – greenapps