How to create bitmap from sdcard images in android? - android

I need to create a bitmap from sdcard images so after getting uri of image i am getting byte data by opening inputStream as follows
public byte[] getBytesFromFile(InputStream is)
{
byte[] data = null;
ByteArrayOutputStream buffer=null;
try
{
buffer = new ByteArrayOutputStream();
int nRead;
data = new byte[16384];
while ((nRead = is.read(data, 0, data.length)) != -1)
{
buffer.write(data, 0, nRead);
}
buffer.flush();
return buffer.toByteArray();
} catch (IOException e)
{
return null;
}
finally
{
if(data!=null)
data = null;
if(is!=null)
try {
is.close();
} catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
if(buffer!=null)
{
try {
buffer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
buffer = null;
}
System.gc();
}
after this i am just creating bitmap of that data by following code
byte[] data = getBytesFromFile(is);
Bitmap bm= BitmapFactory.decodeByteArray(data, 0, data.length);
but it gives me outofmemory error. many peoples guide me to check for memory leakages but, this is the first step in my app., i mean thru intent filter i start my app from gallery menu option "share" which invokes my app with the image uri..
plz guide me guys if i am wrong... and also this exception comes on the devices which have high resolution images(size excceds 1MB), but any how it should create Bitmap...

Try to use the BitmapFactory.decodeStream() method instead of first loading the bytearray into memory. Also check out this question for more info on loading bitmaps.

Related

Proper strategy of getting byte content of big images from Gallery when OutOfMemoryError is thrown

First of all I would like to say, that loading big images strategy is described here. I am aware of the obligation to resize the image to omit OutOfMemoryError. I would like to get bytes from the image to be able to send it through Internet.
public byte[] getAttachment(Context context, String fullFilePath) {
byte[] fileBytes = mFileUtil.readFileAsBytes(fullFilePath);
if (fileBytes == null) {
Logger.i("Unable to get bytes, trying through content resolver");
try {
fileBytes = mFileUtil.readFileFromContentResolver(context, fullFilePath);
} catch (OutOfMemoryError e) {
Uri imageUri = Uri.parse(fullFilePath);
if (checkIfFileIsImage(context, imageUri)) {
try {
InputStream stream = context.getContentResolver().openInputStream(imageUri);
if (stream == null) {
return null;
}
BitmapFactory.Options options = getOptions(stream, 2000, 2000);
stream.close();
stream = context.getContentResolver().openInputStream(imageUri);
if (stream == null) {
return null;
}
Bitmap bitmap = BitmapFactory.decodeStream(stream, null, options);
bitmap = rotateBitmap(context, imageUri, bitmap);
stream.close();
fileBytes = convertBitmapToArray(bitmap);
} catch (Exception e1) {
Logger.e("Unable to get bytes using fallback method, attachment " +
"will not be added");
} catch (OutOfMemoryError e2) {
Logger.e("Unable to get bytes using fallback method, because " +
"attachment is too big. Attachment will not be added");
}
}
System.gc();
}
}
return fileBytes;
}
FileUtil.class
public byte[] readFileAsBytes(String fileName) {
File originalFile = new File(fileName);
byte[] bytes = null;
try {
FileInputStream fileInputStreamReader = new FileInputStream(originalFile);
bytes = new byte[(int) originalFile.length()];
fileInputStreamReader.read(bytes);
} catch (IOException e) {
}
return bytes;
}
public byte[] readFileFromContentResolver(Context context, String fileName) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
InputStream is = null;
InputStream inputStream = null;
try {
inputStream = context.getContentResolver().openInputStream(Uri.parse(fileName));
is = new BufferedInputStream(inputStream);
byte[] data = new byte[is.available()];
is.read(data);
bos.write(data);
} catch (Exception e) {
} finally {
try {
if (is != null) {
is.close();
}
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e1) {
}
}
return bos.toByteArray();
}
As you can see the aim of this code is to get byte[] from Bitmap unlike here. It works without problems in almost any case. However it is especially error prone on low-end devices with older Android systems (but also very rarely).
I don't like the idea of setting largeHeap inside AndroidManifest.xml as this is just masking the problem rather than cope with it. I also would not like to send even smaller images.
Could this piece of code be improved in any other way in order to get rid of OutOfMemoryError?

unable to recursively download images

Hi i am trying to recursively download the images but i am unable to.
It only downloads the first image! does any one know why?
this is my code to download, I did a log to check if there are items in my list and yes, there are 20:
Log.d("imageList.size",String.valueOf(imageList.size()));
try
{
for (int i=0; i<=imageList.size(); i++)
{
String image= imageList.get(i);
Log.d("imageList.get(0)",image);
String filename = String.valueOf(image.hashCode());
Log.v("TAG FILE :", filename);
File f = new File(cacheDir, filename);
// Is the bitmap in our cache?
Bitmap bitmap = BitmapFactory.decodeFile(f.getPath());
if (bitmap != null)
return bitmap;
else {
// Nope, have to download it
try {
bitmap = BitmapFactory.decodeStream(new URL(image)
.openConnection().getInputStream());
// save bitmap to cache for later
writeFile(bitmap, f);
return bitmap;
} catch (FileNotFoundException ex) {
ex.printStackTrace();
Log.v("FILE NOT FOUND", "FILE NOT FOUND");
return null;
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
There seems to be a problem with your for loop, it is exiting on the first iteration of the loop, check your braces and ensure that you have the braces setup the way you intend it and the logic makes sense. You should NOT return until your for loop is done.
Line: 25 in your code, do not return before the loop ends.

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

how to read bytes from a video file in android

I have a question that I want to read bytes from video resided in sdcard in chunk size 1024,
means I have to read 1024 bytes from the file at a time. I am able to fetch number of bytes from the video but I can't get it in chunks, I don't know how to achieve this. Please suggest me the right solution regarding the same.
Thanks in advance.
import java.io.*;
public class FileUtil {
private final int BUFFER_SIZE = 1024;
public void readFile(String fileName) {
BufferedInputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(fileName));
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
}
byte[] buffer = new byte[BUFFER_SIZE];
try {
int n = 0;
while ((n = in.read(buffer, 0, BUFFER_SIZE)) > 0) {
/* do whatever you want with buffer here */
}
}
catch(Exception e) {
e.printStackTrace();
}
finally { // always close input stream
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Based on the code from http://www.xinotes.org/notes/note/648/

Categories

Resources