Download and show the Thumbnail - android

I try to download a picture from URL to SD card/Download.
And I try to show its thumbnail in imageview.
Now I had below code:
try {
Download(URL); //download picture to SD card/Download
File myfile = new File(Environment.getExternalStorageDirectory() + "/Download/", filename);
Drawable photo = null;
photo = Drawable.createFromPath(myfile.getPath());
imageview.setBackgroundDrawable(photo);
}
It show the original picture.
But when the picture is large.
The memory error occurs.
So I want to show the smaller picture.
How should I do to generate the thumbnail and show it?
Or how to use the thumbnail generate by Android system?

Use Bitmap, Something like,
try
{
Download(URL); //download picture to SD card/Download
final int THUMBNAIL_SIZE = 64;
FileInputStream fis = new FileInputStream(Environment.getExternalStorageDirectory() + "/Download/", filename);
Bitmap imageBitmap = BitmapFactory.decodeStream(fis);
imageBitmap = Bitmap.createScaledBitmap(imageBitmap, THUMBNAIL_SIZE, THUMBNAIL_SIZE, false);
imageview.setImageBitmap(imageBitmap);
}
catch(Exception ex) {
}

From the Shown Code
Try this instead your last 2 lines
Bitmap photo = Bitmap.createScaledBitmap(BitmapFactory.decodeFile(myfile.getPath()),60,60,true);
imageview.setImageBitmap(photo);
And if you have made any objects for Bitmap/String/Stream in your Download() function free them calling System.gc();
And I hope this will work.

Related

Android BitmapFactory.decodeFile on jpeg file returns null

My app calls the camera to take a picture and save it into my app local directory (getApplicationContext().getFilesDir()) which works fine.
When I try to convert the picture into a bitmap using BitmapFactory the result is null. This the code I use :
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
String picturePath = pictureFile.getAbsolutePath();
Bitmap bitmap = BitmapFactory.decodeFile(picturePath, options);
Note that pictureFile was created as follows :
pictureFile = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
foodwarnDir /* directory */
);
Didn't you forget add permissions READ_EXTERNAL_STORAGE and/or WRITE_EXTERNAL_STORAGE ?
File locationOfFile = new
File(Environment.getExternalStorageDirectory().getAbsolutePath()+ "/images");
File destination= new File(locationOfFile , fileName + ".JPG");
FileInputStream fileInputStream;
fileInputStream= new FileInputStream(destination);
Bitmap img = BitmapFactory.decodeStream(fileInputStream);
OR
This is my working code in my project here:
View imageHolder = LayoutInflater.from(this).inflate(R.layout.image_item, null);
ImageView thumbnail = (ImageView) imageHolder.findViewById(R.id.media_image);
try {
String path = uri.getPath();
Bitmap bmImg = BitmapFactory.decodeFile(path);
Point p = new Point();
p.set(100, 100);
Bitmap bitmapp = waterMark(bmImg, mRefNo, p, Color.RED, 90, 60, true);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmapp.compress(Bitmap.CompressFormat.PNG, 100, stream);
Glide.with(this)
.load(stream.toByteArray())
.asBitmap()
.error(R.mipmap.ic_launcher)
.into(thumbnail);
mSelectedImagesContainer.addView(imageHolder);
thumbnail.setLayoutParams(new FrameLayout.LayoutParams(wdpx, htpx));
} catch (Exception e) {
e.printStackTrace();
}
Hope this helps you
other helpful Links1 Link2
Create temp file:
File tempFile = File.createTempFile("temp_file, ".jpg", this.getExternalCacheDir());
get path created:
String mPath = tempFile.getAbsolutePath();
now in you activityResult
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
options.inSampleSize = 8;
Bitmap bitmap = BitmapFactory.decodeFile(mPath, options);
use
data.getExtras().get("data");//for getting bitmap
Uri u = intent.getData();// for getting the Uri and get the path from uri
for getting data from your camera
Assuming you're using java.io.File class. According to Java docs function .createTempFile creates empty file on the System.
As such, this file will have only meta info without any content, with zero length, and this is probably a reason why it is not possible to extract Bitmap.
So you need to Create File Object instance instead of actual file, using new File()
You can also use WeakReference and similar to Bitmap you create if you're looking to decrease chance of memory leaks in early implementation.

Load images with OpenCV from assets folder in Android

I'm stuck trying to load an image placed in assets folder with OpenCV 3.0 in Android. I've read a lot of answers here, but I can't figure out what I'm doing wrong.
"my image.jpg" is place directly in the assets folder created by Android Studio.
This is the code I'm using. I've checked and the library has been loaded correctly.
Mat imgOr = Imgcodecs.imread("file:///android_asset/myimage.jpg");
int height = imgOr.height();
int width = imgOr.width();
String h = Integer.toString(height);
String w = Integer.toString(width);
if (imgOr.dataAddr() == 0) {
// If dataAddr() is different from zero, the image has been loaded
// correctly
Log.d(TAG, "WRONG UPLOAD");
}
Log.d(h, "height");
Log.d(w, "width");
When I try to run my app, this is what I get:
08-21 18:13:32.084 23501-23501/com.example.android D/MyActivity: WRONG UPLOAD
08-21 18:13:32.085 23501-23501/com.example.android D/0: height
08-21 18:13:32.085 23501-23501/com.example.android D/0: width
It seems like the image has no dimensions. I guess because it has not been loaded correctly. I'va also tried to load it placing it in the drawable folder, but it doesn't work anyway and I'd prefer to use the assets one.
Anyone can please help me and tell me how to find the right path of the image?
Thanks
Problem: imread needs absolute path and your assets are inside a apk, and the underlying c++ classes cannot read from there.
Option 1: load image into Mat without using imread from drawable folder.
InputStream stream = null;
Uri uri = Uri.parse("android.resource://com.example.aaaaa.circulos/drawable/bbb_2");
try {
stream = getContentResolver().openInputStream(uri);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bmp = BitmapFactory.decodeStream(stream, null, bmpFactoryOptions);
Mat ImageMat = new Mat();
Utils.bitmapToMat(bmp, ImageMat);
Option 2: copy image to cache and load from absolute path.
File file = new File(context.getCacheDir() + "/" + filename);
if (!file.exists())
try {
InputStream is = context.getAssets().open(filename);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
FileOutputStream fos = new FileOutputStream(file);
fos.write(buffer);
fos.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
if (file.exists()) {
image = cvLoadImage(file.getAbsolutePath(), type);
}

Bad image quality when load/save bitmap

I'm working with bitmap and have some problems need to help:
My app works as below:
Load JPG image file(1) from SDcard to bitmap1
Save this bitmap1 to new JPG file(2).
Load new JPG image(2) file to bitmap2
Save bitmap2 to new JPG file(3) ....
.... repeat again and again
Now I can load/save bitmap to file, but problem is quality of image reduces after load/save.
So if I do load/save stuff for 10 times, so my image become ugly.
This is my code:
private void saveBitmapToFile(String imgPath) {
Log.e("Filename-----------------", imgPath);
// Decode image file to bitmap
BitmapFactory.Options options = new BitmapFactory.Options();
// options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(imgPath, options);
// Get filename
long currentMili = System.currentTimeMillis();
currentName = currentMili + "";
String filePath = FOLDER_PATH + currentMili + ".jpg";
// Save bitmap to new file
try {
File file = new File(filePath);
FileOutputStream fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
}
You're re-compressing a lossy file format. You're going to get image artifacts doing that. If you need to do this for some reason, use a lossless format like png.

VuDroid pdf viewer cannot find Bitmap to render or it doesnt render

I am trying to use the VuDroid PDF viewer and I need to take the rendered bitmap and store it as a byte[]. Then I need to convert it back into a Bitmap that can be displayed on a view using something like "canvas.drawBitmap(bitmap, 0, 0, paint);".
I have spent many hours trying to access the Bitmap and I might have done it already, but even if I get the byte[] to return something it still wont render as a Bitmap on the canvas.
Could someone please help me here, I must be missing something. Thank you so much.
I believe it is supposed to accessed via...
PDFPage.java .... public Bitmap renderBitmap(int width, int height, RectF pageSliceBounds)
-or-
through Page.java -or- DocumentView.java -or- DecodeService.java
Like I said I have tried all of these and have gotten results I just cannot see where I am going wrong since I cannot render it to see if the Bitmap was called correctly.
Thank you again :)
The doc says the method returns "null if the image could not be decode." You can try:
byte[] image = services.getImageBuffer(1024, 600);
InputStream is = new ByteArrayInputStream(image);
Bitmap bmp = BitmapFactory.decodeStream(is);
I think This will help you:-
Render a byte[] as Bitmap in Android
How does Bitmap.Save(Stream, ImageFormat) format the data?
Copy image with alpha channel to clipboard with custom background color?
if you want to get each pdf page as independent bitmap you should consider that
VuDroid render the pages,
PDFView only display them.
you should use VuDroid functions.
now you can use this example and create your own codes
Example code : for make bitmap from a specific PDF page
view = (ImageView)findViewById(R.id.imageView1);
pdf_conext = new PdfContext();
PdfDocument d = pdf_conext.openDocument(Environment.getExternalStorageDirectory() + "your PDF path");
PdfPage vuPage = d.getPage(1); // choose your page number
RectF rf = new RectF();
rf.bottom = rf.right = (float)1.0;
Bitmap bitmap = vuPage.renderBitmap(60, 60, rf); //define width and height of bitmap
view.setImageBitmap(bitmap);
for writing this bitmap on SDCARD :
try {
File mediaImage = new File(Environment.getExternalStorageDirectory().toString() + "your path for save thumbnail images ");
FileOutputStream out = new FileOutputStream(mediaImage);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
for retrieve saved image:
File file = new File(Environment.getExternalStorageDirectory().toString()+ "your path for save thumbnail images ");
String path = file.getAbsolutePath();
if (path != null){
view = Bitmap.createScaledBitmap(BitmapFactory.decodeFile(path), YOUR_X, YOUR_Y, false);
}
Try this code to check whether bitmap is properly generating or not
PdfContext pdf_conext = new PdfContext();
PdfDocument d = (PdfDocument) pdf_conext.openDocument(pdfPath);
PdfPage vuPage = (PdfPage) d.getPage(0);
RectF rf = new RectF();
Bitmap bitmap = vuPage.renderBitmap(1000,600, rf);
File dir1 = new File (root.getAbsolutePath() + "/IMAGES");
dir1.mkdirs();
String fname = "Image-"+ 2 +".jpg";
File file = new File (dir1, fname);
if (file.exists ())
file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}

How can I write a Drawable resource to a File?

I need to export some Drawable resources to a file.
For example, I have a function that returns to me a Drawable object. I want to write it out to a file in /sdcard/drawable/newfile.png. How can i do it?
Although the best answer here have a nice approach. It's link only. Here's how you can do the steps:
Convert Drawable to Bitmap
You can do that in at least two different ways, depending on where you're getting the Drawable from.
Drawable is on res/drawable folders.
Say you want to use a Drawable that is on your drawable folders. You can use the BitmapFactory#decodeResource approach. Example below.
Bitmap bm = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.your_drawable);
You have a PictureDrawable object.
If you're getting a PictureDrawable from somewhere else "at runtime", you can use the Bitmap#createBitmap approach to create your Bitmap. Like the example below.
public Bitmap drawableToBitmap(PictureDrawable pd) {
Bitmap bm = Bitmap.createBitmap(pd.getIntrinsicWidth(), pd.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bm);
canvas.drawPicture(pd.getPicture());
return bm;
}
Save the Bitmap to disk
Once you have your Bitmap object, you can save it to the permanent storage. You'll just have to choose the file format (JPEG, PNG or WEBP).
/**
* #param dir you can get from many places like Environment.getExternalStorageDirectory() or mContext.getFilesDir() depending on where you want to save the image.
* #param fileName The file name.
* #param bm The Bitmap you want to save.
* #param format Bitmap.CompressFormat can be PNG,JPEG or WEBP.
* #param quality quality goes from 1 to 100. (Percentage).
* #return true if the Bitmap was saved successfully, false otherwise.
*/
boolean saveBitmapToFile(File dir, String fileName, Bitmap bm,
Bitmap.CompressFormat format, int quality) {
File imageFile = new File(dir,fileName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(imageFile);
bm.compress(format,quality,fos);
fos.close();
return true;
}
catch (IOException e) {
Log.e("app",e.getMessage());
if (fos != null) {
try {
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
return false;
}
And to get the target directory, try something like:
File dir = new File(Environment.getExternalStorageDirectory() + File.separator + "drawable");
boolean doSave = true;
if (!dir.exists()) {
doSave = dir.mkdirs();
}
if (doSave) {
saveBitmapToFile(dir,"theNameYouWant.png",bm,Bitmap.CompressFormat.PNG,100);
}
else {
Log.e("app","Couldn't create target directory.");
}
Obs: Remember to do this kind of work on a background Thread if you're dealing with large images, or many images, because it can take some time to finish and might block your UI, making your app unresponsive.
get the image stored in sdcard..
File imgFile = new File(“/sdcard/Images/test_image.jpg”);
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);
myImage.setImageBitmap(myBitmap);
}
Update:
String path = Environment.getExternalStorageDirectory()+ "/Images/test.jpg";
File imgFile = new File(path);

Categories

Resources