Reading Image from internal memory android gives null pointer exception - android

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

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

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.

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

caching images in android

I want to cache some images when downloaded and when again my application starts, it should check if the images are cached so it returns images otherwise null , so I download and cache them again
I tried using LRU Cache http://developer.android.com/reference/android/util/LruCache.html but it didn't work for me , coz its for API level 12, and I am working on 10.
here is that question
caching images with LruCache
What are the other easy adoptable possible solutions to cache
Check out this for storing your files:
Storage options android sdk
okay I did like this
private Bitmap getFile(String fileName) {
Bitmap file = null;
try {
FileInputStream fis;
fis = openFileInput(fileName);
file = BitmapFactory.decodeStream(fis);
fis.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return file;
}
protected void putFile(Bitmap bitmap, String fileName){
FileOutputStream fos;
try {
fos = openFileOutput(fileName, Context.MODE_PRIVATE);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected String doInBackground(Void... params) {
for (int i = 0; i < HomeActivity.globalObj.categoriesList.size(); i++) {
Bitmap b;
b = getFile(HomeActivity.globalObj.categoriesList.get(i).name);
if (b == null) {
b = getImageBitmap(HomeActivity.globalObj.categoriesList.get(i).large_image);
putFile(b, HomeActivity.globalObj.categoriesList.get(i).name);
}
ImageView iv = new ImageView(getApplicationContext());
iv.setImageBitmap(b);
imageViewList.add(iv);
}

How to create bitmap from sdcard images in 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.

Categories

Resources