Load bitmap from SD card don't work - android

I have some problem show images from sd card, i try to load bitmap into imageview.
This is the code to load image:
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
File imagen1 = new File(ruta + contratoActual.getImgDoc1());
if (imagen1.exists()) {
try {
bmap = BitmapFactory.decodeStream(new FileInputStream(imagen1), null, options);
ByteArrayOutputStream out = new ByteArrayOutputStream();
bmap.compress(Bitmap.CompressFormat.PNG, 100, out);
decoded[0] = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));
} catch (FileNotFoundException e) {
Log.e("ERROR", e.getMessage());
}
load bitmap into image view:
LayoutParams p = (LayoutParams) img1.getLayoutParams();
p.width = 250;
p.height = 190;
if (result[0] != null) {
img1.setImageBitmap(result[0]);
img1.setScaleType(ImageView.ScaleType.CENTER_CROP);
img1.setLayoutParams(p);
result[0].recycle();
}
and here show the result:
and i have this log result:

Try this inside your code:
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap YourBitmap = BitmapFactory.decodeFile(YourImagePath, options);
Example
File Read Permission:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Related

Bitmap not setting in imageView random issue

I am trying to fetch file from device storage and showing it in image view .
Sometimes it is working perfectly fine, but sometimes not. Although bitmap is there but image view remains black.
Kindly suggest.
storage file Location
file:/storage/emulated/0/Download/Full-hd-nature-wallpapers-free-download2.jpg
method which is returning bitmap
public static Bitmap convertToBitmap(File file) {
URI uri = null;
try {
uri = file.toURI();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 1;
Bitmap bmp = BitmapFactory.decodeStream(uri.toURL().openStream(), new Rect(), options);
//bmp.recycle();
return bmp;
} catch (Exception e) {
return null;
}//catch
}
setting image
imageViewPatientImage.setImageBitmap(convertToBitmap(new File(mImagePath));
Try this:
Bitmap bitmap = getThumbnail(uri);
showImage.setImageBitmap(bitmap);
Pass Bitmap for Optimization:
public Bitmap getThumbnail(Uri uri) throws FileNotFoundException, IOException{
InputStream input = getContext().getContentResolver().openInputStream(uri);
BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options();
onlyBoundsOptions.inJustDecodeBounds = true;
onlyBoundsOptions.inDither=true;//optional
onlyBoundsOptions.inPreferredConfig=Bitmap.Config.ARGB_8888;//optional
BitmapFactory.decodeStream(input, null, onlyBoundsOptions);
input.close();
if ((onlyBoundsOptions.outWidth == -1) || (onlyBoundsOptions.outHeight == -1))
return null;
int originalSize = (onlyBoundsOptions.outHeight > onlyBoundsOptions.outWidth) ? onlyBoundsOptions.outHeight : onlyBoundsOptions.outWidth;
double ratio = (originalSize > 500) ? (originalSize / 500) : 1.0;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmapOptions.inSampleSize = getPowerOfTwoForSampleRatio(ratio);
bitmapOptions.inDither=true;//optional
bitmapOptions.inPreferredConfig=Bitmap.Config.ARGB_8888;//optional
input = getContext().getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(input, null, bitmapOptions);
input.close();
return bitmap;
}
private static int getPowerOfTwoForSampleRatio(double ratio){
int k = Integer.highestOneBit((int)Math.floor(ratio));
if(k==0) return 1;
else return k;
}

Saving bitmap to SdCard Android

I am writng a code to convert a png file back to bmp and save it on the sdcard. This is my current code.
FileInputStream in;
BufferedInputStream buf;
try {
in = new FileInputStream("File_Path_to_Read.png");
buf = new BufferedInputStream(in);
byte[] bMapArray= new byte[buf.available()];
buf.read(bMapArray);
Bitmap bMap = BitmapFactory.decodeByteArray(bMapArray, 0, bMapArray.length);
//Code segment to save on file
int numBytesByRow = bMap.getRowBytes() * bMap.getHeight();
ByteBuffer byteBuffer = ByteBuffer.allocate(numBytesByRow);
bMap.copyPixelsToBuffer(byteBuffer);
byte[] bytes = byteBuffer.array();
FileOutputStream fileOuputStream = new FileOutputStream("File_Path_To_Save.bmp");
fileOuputStream.write(bytes);
fileOuputStream.close();
if (in != null) {
in.close();
}
if (buf != null) {
buf.close();
}
} catch (Exception e) {
}
I am having problem in saving the bMap to the Sdcard. All the examples I found use bMap.compress(). Using this method I can't save as bmp. Can someone give an example on how to save the bitmap on the Sdcard?
Edit:
I can now save the file as .bmp to sdcard. However it won't get to the original size. Any sugguestions on converting the PNG to BMP?
File root = new File(Environment.getExternalStorageDirectory()
+ File.separator + "My_Folder" + File.separator);
root.mkdirs();
File myFile = new File(root, "ABC.jpg");
Bitmap bitmap = decodeFile(myFile, 800, 600);
OutputStream out = null;
File file = new File(mediaStorageDir.getAbsoluteFile() + "/DEF.jpg");
try {
out = new FileOutputStream(file);
bitmap .compress(Bitmap.CompressFormat.JPEG, 80, out);
out.flush();
out.close();
bitmap.recycle();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
public static Bitmap decodeFile(File f, int WIDTH, int HIGHT) {
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
// The new size we want to scale to
final int REQUIRED_WIDTH = WIDTH;
final int REQUIRED_HIGHT = HIGHT;
// Find the correct scale value. It should be the power of 2.
int scale = 2;
while (o.outWidth / scale / 2 >= REQUIRED_WIDTH
&& o.outHeight / scale / 2 >= REQUIRED_HIGHT)
scale *= 2;
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
}
return null;
}

BitmapFacotry.decodeByteArray returns null for a valid image's byte array

this is an image in the tag of an mp3 file
http://i.stack.imgur.com/HtXqA.jpg
i get this image byte array from mp3 file with Android's MediaMetaDataRetreiver ... when i try to decode this image using BitmapFactory.decodeByteArray it returns null
Help would be apprecciated
EDIT: when i first decode with options.inJustDecodeBounds = true ... options.outWidth and options.outHeight returns the correct width and height
Full Code:
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
retriever.setDataSource(context, songUri);
byte[] data = retriever.getEmbeddedPicture();
if(data != null)
{
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeByteArray(data, 0, data.length, options);
options.inSampleSize = BitmapUtils.calculateInSampleSize(options, 500, 500);
options.inJustDecodeBounds = false;
albumArtBitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options);
}
Use stream instead:
InputStream is;
Bitmap bitmap;
is = context.getResources().openRawResource(R.drawable.someImage);
bitmap = BitmapFactory.decodeStream(is);
try {
is.close();
is = null;
} catch (IOException e) {
}
BTW, I didn't try jpg yet but suppose maybe this is a problem. Try to convert it to "png"

How to get the path of thumbnail in sd card

I use below code to get the file pathof image in sd card.
File[] f = (Environment.getExternalStorageDirectory()).listFiles();
int i;
for(i = 0; i < f.length; i++) {
if(f[i].isFile()) {
if(isPhoto(f[i].getName())) {
Filepath.add(f[i].getAbsolutePath());
}
}
else {
//recursive
}
}
I want to get the path of the thumbnail of image by know original image path.
How to do it?
You can get the Uri from a file like this:
Uri uri = Uri.fromFile(new File("/mnt/images/abc.jpg"));
Bitmap thumbnail = getPreview(uri);
And the following function gives you the thumbnail:
Bitmap getPreview(URI uri) {
File image = new File(uri);
BitmapFactory.Options bounds = new BitmapFactory.Options();
bounds.inJustDecodeBounds = true;
BitmapFactory.decodeFile(image.getPath(), bounds);
if ((bounds.outWidth == -1) || (bounds.outHeight == -1))
return null;
int originalSize = (bounds.outHeight > bounds.outWidth) ? bounds.outHeight
: bounds.outWidth;
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = originalSize / THUMBNAIL_SIZE;
return BitmapFactory.decodeFile(image.getPath(), opts);
}
You can make your own thumbnail image:
byte[] imageData = null;
try
{
final int THUMBNAIL_SIZE = 64;
FileInputStream fis = new FileInputStream(fileName);
Bitmap imageBitmap = BitmapFactory.decodeStream(fis);
imageBitmap = Bitmap.createScaledBitmap(imageBitmap, THUMBNAIL_SIZE, THUMBNAIL_SIZE, false);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
imageData = baos.toByteArray();
}
catch(Exception ex) {
}

Reading an image file into bitmap from sdcard, why am I getting a NullPointerException?

How can I read an image file into bitmap from sdcard?
_path = Environment.getExternalStorageDirectory().getAbsolutePath();
System.out.println("pathhhhhhhhhhhhhhhhhhhh1111111112222222 " + _path);
_path= _path + "/" + "flower2.jpg";
System.out.println("pathhhhhhhhhhhhhhhhhhhh111111111 " + _path);
Bitmap bitmap = BitmapFactory.decodeFile(_path, options );
I am getting a NullPointerException for bitmap. It means that the bitmap is null. But I have an image ".jpg" file stored in sdcard as "flower2.jpg". What's the problem?
The MediaStore API is probably throwing away the alpha channel (i.e. decoding to RGB565). If you have a file path, just use BitmapFactory directly, but tell it to use a format that preserves alpha:
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(photoPath, options);
selected_photo.setImageBitmap(bitmap);
or
http://mihaifonoage.blogspot.com/2009/09/displaying-images-from-sd-card-in.html
It works:
Bitmap bitmap = BitmapFactory.decodeFile(filePath);
Try this code:
Bitmap bitmap = null;
File f = new File(_path);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
try {
bitmap = BitmapFactory.decodeStream(new FileInputStream(f), null, options);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
image.setImageBitmap(bitmap);
I wrote the following code to convert an image from sdcard to a Base64 encoded string to send as a JSON object.And it works great:
String filepath = "/sdcard/temp.png";
File imagefile = new File(filepath);
FileInputStream fis = null;
try {
fis = new FileInputStream(imagefile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap bm = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100 , baos);
byte[] b = baos.toByteArray();
encImage = Base64.encodeToString(b, Base64.DEFAULT);

Categories

Resources