The most efficient way to show the local image in android - android

I am currently work on a magazine like apps. Since there is an option to zoom in(150%, 200%, 250% of original source) , I would prefer not to scale down the image. However , the app will force restart when I try to decode the image because of the out of memory. Are there any suggestion to fix that?
The image are local (SD card) , can be retrieve in any approach, but eventually need to be a bitmap as I use something like cavans.drawbitmap to display it. I tried, input stream-> bytes , input stream->bitmap etc... but are there any most efficient way or at least
I can sure the app does not force restart / close? Thanks
try {
InputStream is = (InputStream) new URL(url).getContent();
try {
return BitmapFactory.decodeStream(is);
} finally {
is.close();
}
} catch (Exception e) {
return BitmapFactory.decodeResource(context.getResources(), defaultDrawable);
}

You should consider using nostra's image loader, it deals with memory quite efficiently, you can specify lots of config stuffs, im using it and its working pretty well for large images aswell

This is what smartImageView(by loopj - you can find him on http://loopj.com/) uses to retrieve files from the drive/sd.
private Bitmap getBitmapFromDisk(String imgID) {
Bitmap bitmap = null;
if(diskCacheEnabled){
String filePath = getFilePath(imgID);
File file = new File(filePath);
if(file.exists()) {
bitmap = BitmapFactory.decodeFile(filePath);
}
}
return bitmap;
}

Related

Download images and save it

I'm working on a school android project.
I need to have a download button which downloads a picture(when we have class)
And after display it in another activity(even in offline mode, and after quiting)
I've tried picasso, but I can't get it to save and use it in offline mode.
For you to support offline mode, You need to Save the image on your disk because when your cache is cleared, The image is cleared as well.
You can easily use Glide to Solve this, also storing on device and retrieving
You can Learn more about Glide here http://inthecheesefactory.com/blog/get-to-know-glide-recommended-by-google/en
/** Download the image using Glide **/
Bitmap theBitmap = null;
theBitmap = Glide.
with(YourActivity.this).
load("Url of your image").
asBitmap().
into(-1, -1).
get();
saveToInternalStorage(theBitmap, getApplicationContext(), "your preferred image name");
/** Save it on your device **/
public String saveToInternalStorage(Bitmap bitmapImage, Context context, String name){
ContextWrapper cw = new ContextWrapper(context);
// path to /data/data/yourapp/app_data/imageDir
String name_="foldername"; //Folder name in device android/data/
File directory = cw.getDir(name_, Context.MODE_PRIVATE);
// Create imageDir
File mypath=new File(directory,name);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
// Use the compress method on the BitMap object to write image to the OutputStream
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
Log.e("absolutepath ", directory.getAbsolutePath());
return directory.getAbsolutePath();
}
/** Method to retrieve image from your device **/
public Bitmap loadImageFromStorage(String path, String name)
{
Bitmap b;
String name_="foldername";
try {
File f=new File(path, name_);
b = BitmapFactory.decodeStream(new FileInputStream(f));
return b;
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
return null;
}
/** Retrieve your image from device and set to imageview **/
//Provide your image path and name of the image your previously used.
Bitmap b= loadImageFromStorage(String path, String name)
ImageView img=(ImageView)findViewById(R.id.your_image_id);
img.setImageBitmap(b);
Thanks to #Droidman :
How to download and save an image in Android
Of course you can perform downloading and managing images by yourself,
but if your project is quite complex already, there are a lot of
libraries around and you do not need to reinvent the wheel. I won't
post code this time since there are a lot of examples, but I'm going
to tell you about 2 most useful libraries (IMO) related to image
downloading.
1) Android Volley. A powerful networking library created by Google and
covered by official documentation. POST'ing or GET'ing data, images,
JSON - volley will manage it for you. Using volley just for image
downloading is a bit of an overkill in my opinion.
2) Picasso
Image downloading and caching, perfect for
ListView/GridView/RecyclerView. Apache 2.0 license.
3) Fresco
Quite a new image loading library created by Facebook. Progressive
JPEG streaming, gifs and more. Apache 2.0
You could use Android Library called Universal Image Loader:
https://github.com/nostra13/Android-Universal-Image-Loader

Grab video thumbnail and show it in a Gridview in android

I am developing a module for which i want to show all the user's videos from sd card into a Gridview. I have grabbed video file paths in usual way (Checking if file or directory and save if its a file) in a arraylist and grabbed its bitmap thumbnail with following code:
Bitmap bmThumbnail = ThumbnailUtils.createVideoThumbnail(VideoValues.get(position).getAbsolutePath(),
Thumbnails.MINI_KIND);
Obviously this code runs in a background thread. But the only problem is that the gribview still freezes a lot while scrolling. According to me the main problem is extracting the bitmap from video, which takes a lot of time. Can anyone suggest me a different way to get bitmap from video and how it in a grid ? I have seen the smooth behavior in other apps like Facebook, etc. But I cannot figure out as to how that can be done.
please use below method for retrive video thumbnail from video
#SuppressLint("NewApi")
public static Bitmap retriveVideoFrameFromVideo(String videoPath)
throws Throwable
{
Bitmap bitmap = null;
MediaMetadataRetriever mediaMetadataRetriever = null;
try
{
mediaMetadataRetriever = new MediaMetadataRetriever();
mediaMetadataRetriever.setDataSource(videoPath);
bitmap = mediaMetadataRetriever.getFrameAtTime();
}
catch (Exception e)
{
throw new Throwable(
"Exception in retriveVideoFrameFromVideo(String videoPath)"
+ e.getMessage());
}
finally
{
if (mediaMetadataRetriever != null)
{
mediaMetadataRetriever.release();
}
}
return bitmap;
}

Android: not optimal Image load

I got this little function that allows me to load an image from a path, named name. It works, the problem is that I have to call this many times, una tantum. Let's say, a dozen of times at the load of a specific activity. It takes few seconds to load them all.
Is it optimal? Is there a lighter way to achieve the same result?
public static Bitmap loadImageFrom(File path, String name)
{
try {
File f = new File(path, name);
return BitmapFactory.decodeStream(new FileInputStream(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
}
I tried adding if(!f.exists()) return null; like this:
public static Bitmap loadImageFrom(File path, String name)
{
try {
File f = new File(path, name);
if(!f.exists()) return null;
return BitmapFactory.decodeStream(new FileInputStream(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
}
I know that is redundant, but I can't remove the Try Catch clause, cause it giving me an error if I do. However, no speed up noticed.
Any suggestion?
It's not that your code is inefficient, as far as I know, loading pictures manually on the main thread will hurt your app's performance. Especially when you have a large amount of pictures and/or using them to populate your ListView or GridView.
Have a look at Picasso or Universal Image Loader, these libraries should help load your pictures efficiently thus speeding up your app.

problems with big drawable jpg image

during a couple of days i've been looking here and on the Internet in many post for a solution on an issue im having loading or moving a large jpg image (located as a drawable reource by now) and I think it's time to ask myself altought there are many questions and solutions very related.
I'm developing a 3D terrain simulation with OpenGL and the problem is that I'm using as terrain texture a quite large jpg image ( 2048x2048 = 1,94 MB ).
Let's look at some workarround I Did:
1st:
Bitmap terrainBitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.terrain, options);
This one crashes inmediately, probably because the image is too big
2nd:
Uri path = Uri.parse("android.resource://com.jgc.my_app/" + R.drawable.terrain);
URL ulrn;ulrn = new URL(path.getPath());
HttpURLConnection con = (HttpURLConnection)ulrn.openConnection();
InputStream is = con.getInputStream();
Bitmap bmp = BitmapFactory.decodeStream(is);
that one probably was a quite silly attempt
3rd:
Bitmap terrainBitmap = BitmapFactory.decodeFile("android.resource://com.jgc.my_app/terrain.jpg", options);
but I'm getting a very frustrating null bitmap as result...
Other workarrounds in mind are, as the drawable resources are "inside" the application, why not to move them to the sd card and decodefile form there, but, the solutions given to move a bitmap or a drawable to the sdcard that I've found always user BitmapFactory.decodeResource(getResources(), R.drawable.terrain, options);
I appreciate any suggestion, since then I'll be working arround other tasks in my proyect.
Thanks in advance
Ok, maybe I've been lucky, here is the n work-arround ind this workd for me:
private static BitmapFactory.Options terrainBitmapOptions = new BitmapFactory.Options();
...
// Set our bitmaps to 16-bit, 565 format.
terrainBitmapOptions.inPreferredConfig = Bitmap.Config.RGB_565;
...
InputStream is = getResources().openRawResource(R.drawable.terrain);
Bitmap terrainBitmap;
try {
terrainBitmap = BitmapFactory.decodeStream(is, null, terrainBitmapOptions);
} finally {
try {
is.close();
} catch (IOException e) {
// Ignore.
}
}
I hope it helps anyone else...

creating a drawable from sd card to set as a background in android

I am trying to use an image from the sd card and set it as the background for a relativelayout. I have tried other solutions that i have found here and elsewhere but they havent seemed to work for me. here is my code. I have commented out other ways that i have tried and didnt work. the only thing that worked for me was using setBackgroudnResource and using a resource from the app, but this was just to test to make sure mRoot was set up correctly. when I have tried all the other ways, it just doesn't set anything. Anyone know what I am doing wrong, or if there is a better way to do this?
//one way i tired...
//String extDir = Environment.getExternalStorageDirectory().toString();
//Drawable d = Drawable.createFromPath(extDir + "/pic.png");
//mRoot.setBackgroundDrawable(d);
//another way tried..
//Drawable d = Drawable.createFromPath("/sdcard/pic.png");
//mRoot.setBackgroundDrawable(d);
//last way i tried...
mRoot.setBackgroundDrawable(Drawable.createFromPath(new File(Environment.getExternalStorageDirectory(), "pic.png").getAbsolutePath()));
//worked, only to verify mRoot was setup correctly and it could be changed
//mRoot.setBackgroundResource(R.drawable.bkg);
You do not load a drawable from SD card but a bitmap. Here is a method to load it with the reduced sampling (quality) so the program will not complain if the image is too large. Then I guess you need to process this bitmap i.e. crop it and resize for the background.
// Read bitmap from Uri
public Bitmap readBitmap(Uri selectedImage) {
Bitmap bm = null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2; //reduce quality
AssetFileDescriptor fileDescriptor =null;
try {
fileDescriptor = this.getContentResolver().openAssetFileDescriptor(selectedImage,"r");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
finally{
try {
bm = BitmapFactory.decodeFileDescriptor(fileDescriptor.getFileDescriptor(), null, options);
fileDescriptor.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return bm;
}
The Uri here can be supplied from a gallery picker activity.
The image then can be saved into application resources and loaded into an imageView
private void saveBackground(Bitmap Background) {
String strBackgroundFilename = "background_custom.jpg";
try {
Background.compress(CompressFormat.JPEG, 80, openFileOutput(strBackgroundFilename, MODE_PRIVATE));
} catch (Exception e) {
Log.e(DEBUG_TAG, "Background compression and save failed.", e);
}
Uri imageUriToSaveCameraImageTo = Uri.fromFile(new File(BackgroundSettings.this.getFilesDir(), strBackgroundFilename));
// Load this image
Bitmap bitmapImage = BitmapFactory.decodeFile(imageUriToSaveCameraImageTo.getPath());
Drawable bgrImage = new BitmapDrawable(bitmapImage);
//show it in a view
ImageView backgroundView = (ImageView) findViewById(R.id.BackgroundImageView);
backgroundView.setImageURI(null);
backgroundView.setImageDrawable(bgrImage);
}
File file = new File( url.getAbsolutePath(), imageUrl);
if (file.exists()) {
mDrawable = Drawable.createFromPath(file.getAbsolutePath());
}
I suggest checking that the drawable is being loaded correctly. Some things to try:
Try using a different image on the sd card
Put pic.png in R.drawable and make sure mRoot.setBackgroundResource() does what you expect
After loading the drawable, check d.getBounds() to make sure it is what you expect

Categories

Resources