How to get the path of thumbnail in sd card - android

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

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

Android create file from drawable

Is there any way to create file from image drawable to send it via MultypartEntity? I having error all the time.
fileUri = Uri.parse("android.resource://com.wellbread/drawable/placeholder_avatar.png");
mCurrentPhotoPath = fileUri.toString();
java.io.FileNotFoundException: android.resource:/com.wellbread/drawable/placeholder_avatar.png: open failed: ENOENT (No such file or directory)
08-25 12:01:53.134 3663-3684/? W/System.errīš• at libcore.io.IoBridge.open(IoBridge.java:456)
Try the following sample code:
Drawable drawable = getResources().getDrawable(R.drawable.ic_action_home);
if (drawable != null) {
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
final byte[] bitmapdata = stream.toByteArray();
String url = "http://10.0.2.2/api/fileupload";
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
// Add binary body
if (bitmapdata != null) {
ContentType contentType = ContentType.create("image/png");
String fileName = "ic_action_home.png";
builder.addBinaryBody("file", bitmapdata, contentType, fileName);
httpEntity = builder.build();
...
}
...
}
try this:
try
{
File f=new File("file name");
InputStream inputStream = getResources().openRawResource(id); // id drawable
OutputStream out=new FileOutputStream(f);
byte buf[]=new byte[1024];
int len;
while((len=inputStream.read(buf))>0)
out.write(buf,0,len);
out.close();
inputStream.close();
}
catch (IOException e){}
}
You can open an InputStream from your drawable resource using following code:
try
{
File f=new File("your file name");
//id is some like R.drawable.b_image
InputStream inputStream = getResources().openRawResource(id);
OutputStream out=new FileOutputStream(f);
byte buf[]=new byte[1024];
int len;
while((len=inputStream.read(buf))>0)
out.write(buf,0,len);
out.close();
inputStream.close();
}
catch (IOException e){}
}
You have to get Bitmap from drawable:
public static Bitmap decodeAndSetWidthHeight(Resources res, int resId, int reqWidth, int reqHeight){
Bitmap btm = BitmapHelper.decodeSampledBitmapFromResource(res, resId, reqWidth, reqHeight);
return decodeAndSetWidthHeight(btm, reqWidth, reqHeight);
}
Then you can create file from bitmap
public static File bitmapToFile(Bitmap bitmap){
File outFile = FileHelper.getImageFilePNG();
FileOutputStream out = null;
try {
out = new FileOutputStream(outFile);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return outFile;
}
UPDATE (sorry, forget to provide some methods):
public static File getImageFilePNG() {
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath() + "/any name folder");
dir.mkdirs();
String fileName = String.format("%d.png", System.currentTimeMillis());
return new File(dir, fileName);
}
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
Log.d("ANT", "options.inSampleSize : " + options.inSampleSize);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
public static Bitmap decodeAndSetWidthHeight(Bitmap btm, int reqWidth, int reqHeight){
Matrix m = new Matrix();
RectF inRect = new RectF(0, 0, btm.getWidth(), btm.getHeight());
RectF outRect = new RectF(0, 0, reqWidth, reqHeight);
m.setRectToRect(inRect, outRect, Matrix.ScaleToFit.FILL);
float[] values = new float[9];
m.getValues(values);
return Bitmap.createScaledBitmap(btm, (int) (btm.getWidth() * values[0]), (int) (btm.getHeight() * values[4]), true);
}

Load bitmap from SD card don't work

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" />

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

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