How does the flush method work? - android

I am new to android so please excuse me for this noob question.
i wanted to save bmp in my external storage after some research i found out that i need to compress the bmp and then use the flush method of FileOutputStream which will save the bmp in my desired location but how does this work and is there any way to use write function by converting the image to raw bytes of data.
File file = new File(folder,s);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
b.compress(Bitmap.CompressFormat.PNG, 100, fos);
try {
fos.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}

Related

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

How to save images from resource to public storage on Android?

I want to save an image from the drawable directory to the download folder in the phone.
The code I was trying is:
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.tradoficial);
File sd = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
String fileName = "test.jpg";
File dest = new File(sd, fileName);
try {
FileOutputStream out;
out = new FileOutputStream(dest);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
But nothing happens on my phone. Is there anything wrong?
Thanks a lot!
in the AndroidManifest.xml file, add <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> under the <manifest> tag

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

Saving jpg to file messes it up

When I save and load a jpg image (with a white background) to external storage, it looks like this:
The code:
Save:
try {
outStream = new FileOutputStream(fileUri);
image.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
        outStream.flush();
      outStream.close();
} catch (Exception e) {
Log.e("cache", e.getMessage());
e.printStackTrace();
}
Load:
Bitmap bm = BitmapFactory.decodeFile(fileUri.toString());
What am I doing wrong? Thanks.
This is the code I use (should work for you):
Save Bitmap:
public void writeBitmapToMemory(String filename, Bitmap bitmap) {
FileOutputStream fos;
// Use the compress method on the Bitmap object to write image to the OutputStream
try {
fos = game.openFileOutput(filename, Context.MODE_PRIVATE);
// Writing the bitmap to the output stream
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
And to read:
public Bitmap readBitmapFromMemory(String filename) {
Bitmap defautBitmap = null;
File filePath = game.getFileStreamPath(filename);
FileInputStream fi;
try {
fi = new FileInputStream(filePath);
defautBitmap = BitmapFactory.decodeStream(fi);
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
return defautBitmap;
}

saving file on sd card, writes file size 0

I have trouble with saving images on sd card. I can see the file on the sd card but file is empty (size 0). I tried saving it on the phone memory and it works fine. Here is my code.
Imagewritter {
public static boolean writeAsJPG(Context context, Bitmap bitmap,
String filename) {
filename = filename + ".jpg";
File path = Environment.getExternalStorageDirectory();
File f = new File(path, filename);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(f);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
fos = context.openFileOutput(filename, Context.MODE_WORLD_READABLE);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d(TAG, "file not found");
return false;
}
bitmap.compress(CompressFormat.JPEG, quality, fos);
try {
fos.flush();
fos.close();
} catch (IOException e) {
Log.d(TAG, "error closing");
e.printStackTrace();
}
}
here is the code where the bitmap comes from.
DrawingView = (drawing) findViewById(R.id.drawing_view);
drawingBitmap = (Bitmap) DrawingView.getBitmap();
String idName = timeStampText;
//save Image as JPG
ImageWritter.writeAsJPG(getApplicationContext(), drawingBitmap, idName);
i think u have to add these permission in manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Get the image in byte array & check the size of that byte array.. I think you getting 0 size byte array.....
The only problem here is that I have two lines for writing the file. Using FileOutputStream and OpenFileOutput. Just remove these lines and it'll be fine.
try {
fos = context.openFileOutput(filename, Context.MODE_WORLD_READABLE);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d(TAG, "file not found");
return false;
}

Categories

Resources