I was using Universal Image Loader library to load a set of images and TouchImageView to allow zooming. I decided to replace Universal Image Loader with picasso. Everything worked fine except now the image zooms around a frame which is slightly bigger than the image.
#Override
public Object instantiateItem(ViewGroup view, int position) {
View imageLayout = inflater.inflate(R.layout.item_pager_image, view, false);
assert imageLayout != null;
TouchImageView imageView = (TouchImageView) imageLayout.findViewById(R.id.image);
final ProgressBar spinner = (ProgressBar) imageLayout.findViewById(R.id.loading);
spinner.setVisibility(View.INVISIBLE);
Picasso.with(getApplicationContext()).setIndicatorsEnabled(false);
Picasso.with(getApplicationContext()).load(images[position]).into(imageView,new Callback() {
#Override
public void onSuccess() {
spinner.setVisibility(View.GONE);
}
#Override
public void onError() {
}
});
view.addView(imageLayout, 0);
return imageLayout;
I have been breaking my head over a few hours for this. Is this some issue TouchImageView has with Picasso? Any help would be appreciable. Thanks.
Mahram Foadi posted here a great solution that work for me too:
Picasso.with(context).load (someUri).into(new Target () {
#Override
public void onBitmapLoaded (final Bitmap bitmap,
final Picasso.LoadedFrom loadedFrom) {
someTouchImageView.setImageBitmap (bitmap);
}
#Override
public void onBitmapFailed (final Drawable drawable) {
Log.d(TAG, "Failed");
}
#Override
public void onPrepareLoad (final Drawable drawable) {
someTouchImageView.setImageDrawable (drawable);
}
});
Hope this helps other people like us to use TouchImageView with Picasso ;)
I figured out the whole issue somehow got fixed when I set the image width and height from wrap_content to fill_parent.
Here is if you are using Glide. Glide is faster in loading than picasso and cheaper in memory consuming
Glide.with(context).load(url).asBitmap().into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
someTouchImageView.setImageBitmap(resource);
}
});
For those who still run into this problem.
As inspired by a comment in this issue:
It's because needs View size and it's not available in TouchImageView implementation before bitmap is set
Load the image after the TouchImageView is created using .post().
Kotlin code:
touchImageView.post { // Load the image when the view is ready
Picasso.get()
.load(file)
.placeholder(R.drawable.image_placeholder)
.into(touchImageView)
}
Java code:
// Load the image when the view is ready
touchImageView.post(new Runnable() {
#Override
public void run() {
Picasso.get()
.load(file)
.placeholder(R.drawable.image_placeholder)
.into(touchImageView)
}
});
Related
I cannot display the image downloaded from the Internet as annotation. I am implementing the following code and Picasso library. However, if I use a local image, it works. Thanks in advance for any help.
private void createAnnotation(int id, double lat, double lon, String caption, String photoUrl) {
SKAnnotation annotation = new SKAnnotation(id);
SKCoordinate coordinate = new SKCoordinate(lat, lon);
annotation.setLocation(coordinate);
annotation.setMininumZoomLevel(5);
SKAnnotationView annotationView = new SKAnnotationView();
View customView =
(LinearLayout) ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
R.layout.annotation_photo_and_text, null, false);
// If width and height of the view are not power of 2 the actual size of the image will be the next power of 2 of max(width,height).
//annotationView.setView(findViewById(R.id.customView));
TextView tvCaption = (TextView) customView.findViewById(R.id.annotation_photo_caption);
tvCaption.setText(caption);
ImageView ivPhoto = (ImageView) customView.findViewById(R.id.annotation_photo);
Picasso.with(getApplicationContext())
.load(photoUrl)
.resize(96, 96)
//.centerCrop()
.into(ivPhoto);
//ivPhoto.setImageResource(R.drawable.hurricanerain);
annotationView.setView(customView);
annotation.setAnnotationView(annotationView);
mapView.addAnnotation(annotation, SKAnimationSettings.ANIMATION_NONE);
}
Picasso loads images from the internet asynchronously. Try adding the image to the Annotation after it has been downloaded. You can use a Target to listen for the image download completion:
ImageView ivPhoto = (ImageView) customView.findViewById(R.id.annotation_photo);
Target target = new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
ivPhoto.setImageBitmap(bitmap);
annotationView.setView(customView);
annotation.setAnnotationView(annotationView);
mapView.addAnnotation(annotation, SKAnimationSettings.ANIMATION_NONE);
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {}
};
ivPhoto.setTag(target);
Picasso.with(getApplicationContext())
.load(photoUrl)
.resize(96, 96)
.into(target);
try activity context in place of applicationcontext. It may work for you.
What if you try to load image using Target object, and then set downloaded bitmap to your ImageView?
Target target = new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
// loading of the bitmap was a success
// TODO do some action with the bitmap
ivPhoto.setImageBitmap(bitmap);
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
// loading of the bitmap failed
// TODO do some action/warning/error message
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
};
ivPhoto.setTag(target);
Picasso.with(getApplicationContext())
.load(photoUrl)
.resize(96, 96)
.into(target);
I have this method, everything is worked perfectly but images always got from server and not load from cache! what happened ?
public static void makeImageRequest(String Unique_ID, final View parentView, final int id) {
String url = FILE_UPLOAD_FOLDER + Unique_ID + ".png";
final int defaultImageResId = R.drawable.user;
// Retrieves an image specified by the URL, displays it in the UI.
ImageCacheManager.getInstance().getImage(url, new ImageListener() {
#Override
public void onErrorResponse(VolleyError error) {
ImageView imageView = (ImageView) parentView.findViewById(id);
imageView.setImageResource(defaultImageResId);
}
#Override
public void onResponse(ImageContainer response, boolean isImmediate) {
if (response.getBitmap() != null) {
ImageView imageView = (ImageView) parentView.findViewById(id);
imageView.setImageBitmap(response.getBitmap());
} else if (defaultImageResId != 0) {
ImageView imageView = (ImageView) parentView.findViewById(id);
imageView.setImageResource(defaultImageResId);
}
}
});
}
Just use Picasso instead ImageCacheManager. Picasso is a powerful image downloading and caching library for Android. Images add much-needed context and visual flair to Android applications. Picasso allows for hassle-free image loading in your application—often in one line of code!
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
Here also can manage whether the image is successfully downloaded or it fails:
Picasso.with(context)
.load("http://i.imgur.com/DvpvklR.png")
.into(imageView, new Callback() {
#Override
public void onSuccess() {
// your code
}
#Override
public void onError() {
// your code
}
});
You should only add this line in your gradle:
compile 'com.squareup.picasso:picasso:2.5.2'
Hope it helps!
I'm trying to load an url into an ImageView but Target doesn't seem to work like what I found told me. Below is my code:
ImageView methodButton= (ImageView) View.inflate(context, R.layout.view_home_scroll_view_image, null);
setMethodPicture(sectionModel.getContent().get(0).getThumbnail(), methodButton);
methodsContainer.addView(methodButton);
and
private void setMethodPicture(final String methodPicture, final ImageView methodButton){
methodButton.setBackgroundColor(0x000000);
if (!StringUtils.isEmpty(methodPicture)) {
Target target = new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
methodButton.setImageBitmap(bitmap);
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
#Override
public boolean equals(Object o) {
return methodPicture.equals(o);
}
#Override
public int hashCode() {
return methodPicture.hashCode();
}
};
Picasso.with(context).load(methodPicture).into(target);
}
}
This doesn't load the picture to the imageView, but when i do this,
ImageView methodButton= (ImageView) View.inflate(context, R.layout.view_home_scroll_view_image, null);
methodButton.setBackgroundColor(0x000000);
Picasso.with(context).load(sectionModel.getContent().get(0).getThumbnail()).into(methodButton);
methodsContainer.addView(methodButton);
it loads the picture.
I want to do the first one so I can change the Bitmap I get before I put it in the ImageView, like changing the width and height, but basing on the original dimensions.
I found the issue, Picasso holds a Weak Reference to the Target. The correct answer can be found here: onBitmapLoaded of Target object not called on first load
Use Glide instead, it provide predefine constrain options which you can add with it
https://github.com/bumptech/glide
I have one ImageView and one image loaded in it with Glide:
Glide.with(ImageView.getContext())
.load(url)
.dontAnimate()
.placeholder(R.drawable.placeholder)
.signature(stringSignature)
.into(new GlideDrawableImageViewTarget(ImageView) {
#Override
public void onResourceReady(GlideDrawable drawable, GlideAnimation anim) {
super.onResourceReady(drawable, anim);
progressBar.setVisibility(View.GONE);
}
});
and when I want refresh the image, I run this same code again only with new signature. It's working perfectly, but when new loading is started, the visible image is gone immediately.
Question
Is possible keep the image in ImageView and replace it after new image is downloaded?
That's the expected behavior.
Each time you call .load(x), Glide call .clear() on the target and its associated request.
That's how Glide is able to handle its pool of Bitmaps, otherwise it would have no way to know when to recycle a Bitmap.
In order to implement this, you need to switch between two Targets, here is the core idea :
public <T> void loadNextImage(#NonNull T model,
#NonNull BitmapTransformation... transformations) {
//noinspection MagicNumber
int hash = model.hashCode() + 31 * Arrays.hashCode(transformations);
if (mLastLoadHash == hash) return;
Glide.with(mContext).load(model).asBitmap().transform(transformations).into(mCurrentTarget);
mLastLoadHash = hash;
}
Target mCurrentTarget;
private class DiaporamaViewTarget extends ViewTarget<ImageView, Bitmap> {
#Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
mLoadedDrawable = new BitmapDrawable(mImageView.getResources(), resource);
// display the loaded image
mCurrentTarget = mPreviousTarget;
You can set loaded Drawable as placeholder in next loading, like this:
private Drawable placeholder = ContextCompat.getDrawable(ctx, R.drawable.placeholder);
public void loadImage(String url, ImageView imageView) {
Glide.with(imageView.getContext())
.load(url)
.placeholder(placeholder)
.into(new GlideDrawableImageViewTarget(imageView) {
#Override
public void onResourceReady(GlideDrawable drawable, GlideAnimation anim) {
super.onResourceReady(drawable, anim);
placeholder = drawable;
}
});
}
I want to load large bitmaps efficiently in my Image Switcher and i have been using Picasso for this purpose but now i am stuck at this point. Without Picasso a lot of OOMs and other nasty exceptions please tell me if I can use this library with Image Switcher too.
If yes then provide sample code.
Thanks!
imswitch.setFactory(new ViewFactory() {
#Override
public View makeView() {
ImageView imageView = new ImageView(getApplicationContext());
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
imageView.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
return imageView;
}
} );
And onClick:
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
currentIndex++;
// If index reaches maximum reset it
if(currentIndex==messageCount)
currentIndex=0;
ImageView imageView = (ImageView)findViewById(R.id.imswitch);
Picasso.with(getApplicationContext()).load(imageIds[currentIndex]).into(imageView);
Toast.makeText(getApplicationContext(), "Pressed "+currentIndex,Toast.LENGTH_LONG).show();
}
One of the possible way is to create own implementation using Target interface.
https://square.github.io/picasso/javadoc/com/squareup/picasso/Target.html
public class ImageSwitcherPicasso implements Target {
private ImageSwitcher mImageSwitcher;
private Context mContext;
public ImageSwitcherPicasso(Context context, ImageSwitcher imageSwitcher){
mImageSwitcher = imageSwitcher;
mContext = context;
}
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom loadedFrom) {
mImageSwitcher.setImageDrawable(new BitmapDrawable(mContext.getResources(), bitmap));
}
#Override
public void onBitmapFailed(Drawable drawable) {
}
#Override
public void onPrepareLoad(Drawable drawable) {
}
}
Than just use as follow
ImageSwitcherPicasso mImageSwitcherPicasso = new ImageSwitcherPicasso(getActivity(), playerBackground);
Picasso.with(getActivity()).load(new File(path)).into(mImageSwitcherPicasso);
where playerBackground is reference to ImageSwitcher