How to convert a bitmap into a File android? [duplicate] - android

This question already has answers here:
Save bitmap to location
(19 answers)
Closed 6 years ago.
I have an image in drawable. I just need to convert this image into a file. How can i achieve this?

Try this it works:--
private File saveBitmap(Bitmap bitmap, String path) {
File file = null;
if (bitmap != null) {
file = new File(path);
try {
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(path); //here is set your file path where you want to save or also here you can set file object directly
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream); // bitmap is your Bitmap instance, if you want to compress it you can compress reduce percentage
// PNG is a lossless format, the compression factor (100) is ignored
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (outputStream != null) {
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
return file;
}

Related

How to convert binary string to bitmap?

I am new to android. I am getting one issue as passing my image as binary in api using retrofit but while getting same binary string of image in response not able to convert binary string to Bitmap again. Below i am passing the binary string getting in response. Its a great help if anyone can help me.
"????\u0000\u0010JFIF\u0000\u0001\u0001\u0000\u0000H\u0000H\u0000\u0000??\u0000\u0011\b\u0002X\u0002?\u0003\u0001\"\u0000\u0002\u0011\u0001\u0003\u0011\u0001??\u0000\u001f\u0000\u0000\u0001\u0005\u0001\u0001\u0001\u0001\u0001\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b??\u0000?\u0010\u0000\u0002\u0001\u0003\u0003\u0002\u0004\u0003\u0005\u0005\u0004\u0004\u0000\u0000\u0001}\u0001\u0002\u0003\u0000\u0004\u0011\u0005\u0012!1A\u0006\u0013Qa\u0007\"q\u00142???\b#B??\u0015R??$3br?\t\n\u0016\u0017\u0018\u0019\u001a%&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz???????????????????????????????????????????????????????????????????????????\u0000\u001f\u0001\u0000\u0003\u0001\u0001\u0001\u0001\u0001\u0001\u0001\u0001\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b??\u0000?\u0011\u0000\u0002\u0001\u0002\u0004\u0004\u0003\u0004\u0007\u0005\u0004\u0004\u0000\u0001\u0002w\u0000\u0001\u0002\u0003\u0011\u0004\u0005!1\u0006\u0012AQ\u0007aq\u0013\"2?\b\u0014B????\t#3R?\u0015br?\n\u0016$4?%?\u0017\u0018\u0019\u001a&'()*56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz
use this code,
String dataValue="";
byte[] bytes = dataValue.getBytes();
Bitmap bmp= BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
Try with this.
You can write the byte array directly to file and do whatever you want with the file:
public void writeToFile(byte[] data, String fileName) throws IOException{
FileOutputStream out = new FileOutputStream(fileName);
out.write(data);
out.close();
}
Also if you have binary stream instance, you can create a bitmap instance directly from the stream, you can use BitmapFactory and convert to bitmap:
Bitmap image = BitmapFactory.decodeStream(stream);
You can download the image file using the following function, where body is retrofit2.0 responsebody instance:
private void DownloadImage(ResponseBody body) {
try {
InputStream in = null;
FileOutputStream out = null;
try {
in = body.byteStream();
out = new FileOutputStream("/sdcardpath" + "imagefilename.jpg");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}

(android) how to overwrite image on DCIM folder?

I already have a resized bitmap object.
with this bitmap, how can i overwrite this bitmap in DCIM folder??
I know that I should change the bitmap into File object...
please help me
(Assume that i also have the absolute path)
I tried this with the code below.
It creates a new file only if a file with same name doesn't exist.
Otherwise, it doesn't create a new file.
private void SaveBitmapToFileCache(Bitmap bitmap, String strFilePath) {
File fileCacheItem = new File(strFilePath);
OutputStream out = null;
try
{
fileCacheItem.createNewFile();
out = new FileOutputStream(fileCacheItem);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
try
{
out.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Try something like this:
//File file= new File("FilePath"+ "/myfolder/myimage.jpg");
if(fileCacheItem .exists())
{
file.delete();
}

How to save image file in android?

I am reading a image file into a byte array.This byte array i have to save again as a image file onto the sdcard.To read the file i have used the following code:
public void readimage()
{
InputStream ins_image = getResources().openRawResource(R.drawable.btn_cancel);
outputStream=new ByteArrayOutputStream();
try
{
ins_image.available();
} catch (IOException e) { e.printStackTrace(); }
try
{
Log.e( "Size of image", ""+ins_image.available());
} catch (IOException e) {e.printStackTrace();}
int size = 0;
byte[] buffer_image = new byte[200000];
try {
while((size=ins_image.read(buffer_image,0,200000))>=0)
{
outputStream.write(buffer_image,0,size);
}
} catch (IOException e) { e.printStackTrace(); }
int length_of_image= outputStream.toByteArray().length;
byte_image=outputStream.toByteArray();
Log.e("Size of image",""+length_of_image);
}
And the below code to save the file:
public void saveimage_fromarray()
{
File photo=new File(Environment.getExternalStorageDirectory(), "photo.png");
if (photo.exists())
{
photo.delete();
}
try
{
FileOutputStream fos=new FileOutputStream(photo.getPath());
fos.write(byte_image[0]);
fos.close();
}
catch (java.io.IOException e)
}
However the file is being saved but it does not display anything.Can somebody please tell me why is it so?
Set the size of the image you are getting in place of 0.
fos.write(byte_image[0]);
Seems like you're writing only one byte of the image.
fos.write(byte_image[0]);
Please compare source file, byte buffer, array and output file sizes.
why don't you simplify everything and just calls this method:
bmp.compress(Bitmap.CompressFormat.PNG, 100, <pass here a valid file outputstream>);

Reading Image from internal memory android gives null pointer exception

I am quite new to android. I want to save image to internal memory and later retrieve the image from internal memory and load it to image view. I have successfully stored the image in internal memory using the following code :
void saveImage() {
String fileName="image.jpg";
//File file=new File(fileName);
try
{
FileOutputStream fOut=openFileOutput(fileName, MODE_PRIVATE);
bmImg.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
}
catch (Exception e)
{
e.printStackTrace();
}
}
using this code image is saved. But when i try to retrieve the image it gives me error. The code used to retrieve the image is :
FileInputStream fin = null;
ImageView img=new ImageView(this);
try {
fin = openFileInput("image.jpg");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] bytes = null;
try {
fin.read(bytes);
} catch (Exception e) {
e.printStackTrace();
}
Bitmap bmp=BitmapFactory.decodeByteArray(bytes,0,bytes.length);
img.setImageBitmap(bmp);
But i get a Null pointer exception.
I checked the file is there in internal memory at path :
/data/data/com.test/files/image.jpg
What am i doing wrong please help me out with this. I have gone through a lot of stack questions.
it is because your bytes array is null, instantiate it, and assign size.
byte[] bytes = null; // you should initialize it with some bytes size like new byte[100]
try {
fin.read(bytes);
} catch (Exception e) {
e.printStackTrace();
}
Edit 1: I am not sure but you can do something like
byte[] bytes = new byte[fin.available()]
Edit 2 : here is a better solution, as you are reading Image,
FileInputStream fin = null;
ImageView img=new ImageView(this);
try {
fin = openFileInput("image.jpg");
if(fin !=null && fin.available() > 0) {
Bitmap bmp=BitmapFactory.decodeStream(fin)
img.setImageBitmap(bmp);
} else {
//input stream has not much data to convert into Bitmap
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Helped by - Jason Robinson

How to receive byte array from Bluetooth and save byte array to SD card as an image file

I am working on an Android Application which needs to implement the Bluetooth functionality. It needs to receive an image from an external h/w device, and then save that byte array to SD card as an image file.
Here is my code:
public void run(){
Log.i(TAG, "BEGIN mConnectedThread");
byte[] buffer = new byte[4096];
//CREATE IMAGE FILE
File test=new File(Environment.getExternalStorageDirectory(), "test.jpg");
if (test.exists()) {
test.delete();
}
try {
fos = new FileOutputStream(test.getPath());
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
/*mEmulatorView.write(buffer, bytes);
// Send the obtained bytes to the UI Activity
mHandler.obtainMessage(BlueTerm.MESSAGE_READ, bytes, -1, buffer).sendToTarget();*/
//receivedData = new String(buffer);
receivedData=new String(buffer)
//WRITE BYTES TO FILE
try {
fos.write(buffer);
}
catch (java.io.IOException e) {
Log.e("PictureDemo", "Exception in photoCallback", e);
}
/*
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeByteArray(buffer , 0, buffer.length);
} catch (OutOfMemoryError e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
if(bitmap != null)
testModeOnScreen.saveBitmapToSdcardAndEmail(bytes, bitmap);
*/}
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
connectionLost();
break;
}
}
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
My problem is that I am not getting any exception or crashes, but I am getting a corrupted image file.
There seem to be multiple issues here. For starters, garbage at the buffer tail, "Let k be the number of bytes actually read; these bytes will be stored in elements b[0] through b[k-1], leaving elements b[k] through b[b.length-1] unaffected":
http://docs.oracle.com/javase/6/docs/api/java/io/InputStream.html#read()
Also, you may happen to need to use the bitmap functionality from Android.
Look how they exchange bitmaps here:
http://kamrana.wordpress.com/2012/05/12/sending-images-over-bluetooth-in-android/
And how they save to a file:
Save bitmap to file function
http://developer.android.com/reference/android/graphics/Bitmap.html#compress(android.graphics.Bitmap.CompressFormat, int, java.io.OutputStream)
You could find it easier hacking together those building blocks than reinventing them.
check this solution;)
String TAG="IMG";
File path = Environment.getExternalStoragePublicDirectory(("/mnt/exSdCard/RecievedIMAGE"));
File file = new File(path, "test.jpg");
BufferedInputStream bufferedInputStream = null;
try {
// Make sure that this path existe if it is not so create it
path.mkdirs();
bufferedInputStream = new BufferedInputStream(inputStream);
OutputStream os = new FileOutputStream(file);
final byte[] buffer = new byte[2048];
int available = 0;
while ((available = bufferedInputStream.read(buffer)) >= 0) {
os.write(buffer, 0, available);
}
bufferedInputStream.read(buffer);
bufferedInputStream.close();
os.close();
Log.d(TAG, "success" + buffer);
} catch (IOException e) {
// Unable to create file, likely because external storage is
// not currently mounted.
Log.w("ExternalStorage", "Error writing " + file, e);
}

Categories

Resources