android save-Lazy List HashMap - android

I want to Serialize the Hash-Map of Default Lazy-list code and store it in a file on device..
Actually I want the images to be locally stored,,,,
As,my project contain a lot's of images to be used from server.... Please provide a way or code for modified lazy-list that stores the Hash-Map in a file.. As next time when app restart the Image-loader class must have that object so,,that image is not downloaded from server...

Make a variable named cacheDir and change getBitmap() method of ImageLoader class to this below one
private Bitmap getBitmap(String urlString)
{
String filename = String.valueOf(urlString.substring(urlString.lastIndexOf("/") + 1));
File f = new File(cacheDir, filename);
try
{
if(!f.exists())
{
Bitmap bitmap = null;
InputStream is = new URL(urlString).openStream();
OutputStream os = new FileOutputStream(f);
Globals.CopyStream(is, os);
os.close();
bitmap = decodeFile(f);
return bitmap;
}
else
{
Bitmap bitmap = decodeFile(f);
return bitmap;
}
}
catch (Exception ex)
{
ex.printStackTrace();
BitmapDrawable mDrawable = (BitmapDrawable) context.getResources().getDrawable(R.drawable.placeholder);
return mDrawable.getBitmap();
}
}

Related

Get and display image in android from inputstream

Starting off by saying I'm new to the Android language and I need help with something.
I'm trying to get an image from an inputstream connected to my java program and save it to the internal storage and after that I display it. However I'm not recieving any errors at all from my code and yet the image is not displaying at all. There is no problem with my Java program/file since it works 100% with another program I wrote in Java which does the same thing Im trying to do with my Android Application.
public void GetImage()
{
try
{
InputStream inputStream = new BufferedInputStream(connectionSocket.getInputStream());
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
FileOutputStream out = new FileOutputStream(getFilesDir() + "james.png");
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
}
catch (IOException e)
{
Log.d("ERROR", "GetImage: " + e);
}
}
public void DisplayImage()
{
ImageView myImageview = (ImageView) findViewById(R.id.myImageView);
int imageResource = getResources().getIdentifier(getFilesDir() + "james.png", null, this.getPackageName());
myImageview.setImageResource(imageResource);
}
Can anyone take a look at the code and tell me what I'm doing wrong? Thank you
File imgFile = new File(getFilesDir() + "james.png");
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageView myImageview = (ImageView) findViewById(R.id.myImageView);
myImageview.setImageBitmap(myBitmap);
}
Please replace your method code with it

BitmapFactory cannot decode an image

In a React Native app for Android, I am trying to write an image (passed as base64) onto the filesystem and later decode it using BitmapFactory.
Why is BitmapFactory still unable to decode the image after using (Base64.decode) while storing it?
The error:
Cannot decode bitmap:
file:///data/data/com.reactnativeapp/files/rct-image-store/1
The custom written method storing the image:
#ReactMethod
public void addImageFromBase64(String base64_image_data, Callback successCallback, Callback failureCallback){
String imageStorageDir = this.reactContext.getApplicationContext().getFilesDir()+"/rct-image-store/";
String file_uri = imageStorageDir+"1";
try {
File f = new File(imageStorageDir);
if(!f.exists()) {
f.mkdir();
}
FileOutputStream fos = new FileOutputStream(file_uri, false);
byte[] decodedImage = Base64.decode(base64_image_data, Base64.DEFAULT);
fos.write(decodedImage);
fos.close();
successCallback.invoke("file://"+file_uri);
} catch (IOException ioe) {
failureCallback.invoke("Failed to add image from base64String"+ioe.getMessage());
} catch (Exception e) {
failureCallback.invoke("Failed to add image from base64String"+e.getMessage());
}
}
Shortened method for accessing the image (fullResolutionBitmap is null):
InputStream inputStream = mContext.getContentResolver().openInputStream(Uri.parse(uri));;
BitmapFactory.Options outOptions = new BitmapFactory.Options();
Bitmap fullResolutionBitmap = BitmapFactory.decodeStream(inputStream, null, outOptions);/// fullResolutionBitmap==null
Here is the image, the bottom part looks cropped. Since both original and converted image have the grey area, the problem seems to be not with the conversion of the image, but with the source (camera).
Original image:
Converted image:

Downloading Images Directly From Android Activity

I'm showing images in my app and I want to add download button after every images when user click on it, image will automatically save to folder. Is it possible?
If you already have the file saved in your application, copy it to this public folder
File imagePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
Then use the technique provided here to scan the picture into the Gallery. Now when the user opens the Gallery they'll see the picture.
I tried Universal Image Loader And Picasso before.
you see that you need and witch one is enough to you.
also to have better decision read this one and this one.
it may help you :
you can use Glide for download image and i think it is better then picasso because it extends picasso.and for more information please see https://github.com/bumptech/glide.
for this you just have to include compile 'com.github.bumptech.glide:glide:3.6.1' into dependencies and then simply add this code line
Glide.with(this).load("http://goo.gl/gEgYUd").into(imageView);`
where http://goo.gl/gEgYUd is URL to pass.and after using this you have not to maintain cache.
enjoy your code:)
private static void persistImage(Bitmap bitmap, String name) {
File filesDir = getAppContext().getFilesDir();
File imageFile = new File(filesDir, name + ".jpg");
OutputStream os;
try {
os = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
os.flush();
os.close();
} catch (Exception e) {
Log.e(getClass().getSimpleName(), "Error writing bitmap", e);
}
}
You can use Picasso library to display images. Add this below code in your build.gradle dependencies:
compile 'com.squareup.picasso:picasso:2.4.0'
Now use this to display images,You can add this code inside the onClick() method of your button.
File file = new File(imagePath);
if(file.exists()) {
Picasso.with(context).load(file).skipMemoryCache().placeholder(R.drawable.placeholder).into(yourImageView);
}
else {
Picasso.with(context).load(imageUrl).skipMemoryCache().placeholder(R.drawable.placeholder).into(yourImageView, new PicassoCallBack(yourImageView,imagePath));
}
The picassoCallBack class will look like this :
public class PicassoCallBack extends Callback.EmptyCallback {
ImageView imageView;
String filename;
public PicassoCallBack(ImageView imageView, String filename) {
this.imageView = imageView;
this.filename = filename;
}
#Override public void onSuccess() {
// Log.e("picasso", "success");
Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
try {
ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos1);
// FileOutputStream outStream = context.openFileOutput(filename, Context.MODE_PRIVATE);
File file = new File(filename);
FileOutputStream outStream = new FileOutputStream(file);
outStream.write(baos1.toByteArray());
outStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onError() {
Log.e("picasso", "error");
}
}
Hope it will do your job.

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

How to display bitmap from internal storage?

I saved my bitmap images in my internal storage but i can't redisplay it. I've been researching for a long time but i've not find yet.
public static void saveImages(Activity activity) throws IOException
{
for (int i=0; i<categories.getItems().length; i++) {
OutputStream os2 = activity.openFileOutput(categories.getItems()[i].getName(),
Context.MODE_WORLD_READABLE);
OutputStreamWriter osw2 = new OutputStreamWriter(os2);
Bitmap bmp = ((BitmapDrawable)categories.getItems()[i].getCategoryImage()).getBitmap();
bmp.compress(Bitmap.CompressFormat.PNG, 90, os2);
osw2.close();
}
}
This code works succesfully to save images. I will redisplay that images from files.
Thank you
Try this code: uses openFileInput to fetch the streams you saved and then decodes them:
for (int i=0; i<categories.getItems().length; i++) {
InputStream is = activity.openFileInput(categories.getItems()[i].getName());
Bitmap b = BitmapFactory.decodeStream(is);
// do whatever you need with b
}
Try this
File f=new File(yourdir, imagename);
Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
decode bitmap, and then make a new imageView then add the bitmap to the imageView.

Categories

Resources