Getting a Bitmap from a SVG Url resource - android

I'm trying to use Glide to get a SVG resource from a URL, but I don't know how to get a Bitmap object instead of loading it in into a View.
The reason for that is that I need to load some SVG files on a Widget.
I used this example: https://stackoverflow.com/a/30938082/3346625
UPDATE 1:
Setup GenericRequestBuilder
final RemoteViews fViews = views;
final int fViewId = viewId;
Runnable myRunnable = new Runnable() {
#Override
public void run() {
GenericRequestBuilder<Uri, InputStream, SVG, Bitmap> requestBuilder;
requestBuilder = Glide.with(mContext)
.using(Glide.buildStreamModelLoader(Uri.class, mContext), InputStream.class)
.from(Uri.class)
.as(SVG.class)
.transcode(new SvgBitmapTranscoder(), Bitmap.class)
.sourceEncoder(new StreamEncoder())
.cacheDecoder(new FileToStreamDecoder<SVG>(new SvgDecoder()))
.decoder(new SvgDecoder())
.placeholder(R.drawable.ic_launcher)
.error(R.drawable.no_icon)
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.load(Uri.parse(url));
requestBuilder.into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
fViews.setImageViewBitmap(fViewId, resource);
}
});
}
};
mainHandler.post(myRunnable);
I had to use a Runnable as requestBuilder.into needs to run on the main thread.
How can I get a Bitmap to later use it with a RemoteView?

Try this:
.transcode(new SvgBitmapTranscoder(), Bitmap.class)
.into(new SimpleTarget<Bitmap>(sizeW, sizeH) {
#Override public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
// update RemoteViews with resource
}
})
SvgBitmapTranscoder should be fairly trivial if there's an svg.renderToBitmap() method.

Related

Image load fail using Picasso,Glide,Image Loader ,Universal Image Loader

i have creating Hindi video song application, but video thumb can't display in video list.
(Single image are loaded but multiple image array can't load.)
using multiple image loader library but doesn't load image:
Glide:
implementation 'com.github.bumptech.glide:glide:4.10.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.10.0'
Glide .with(viewHolder.icon_1.getContext())
.load(((AppModelicon) this.b.get(i)).getThumnail())
.into(viewHolder.icon_1) ;
Glide.with(MainActivity.this)
.load("https://img.youtube.com/vi/EEX_XM6SxmY/mqdefault.jpg")
.placeholder(R.drawable.ic_menu_camera)
.error(R.drawable.ic_menu_gallery)
.listener(new RequestListener<Drawable>() {
#Override
public boolean onLoadFailed(#Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
// log exception
Log.e("TAG", "Error loading image", e);
return false; // important to return false so the error placeholder can be placed
}
#Override
public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
return false;
}
})
.into(viewHolder.icon_1);
Picasso:
implementation 'com.squareup.picasso:picasso:2.+'
Picasso.get()
.load("https://img.youtube.com/vi/EEX_XM6SxmY/mqdefault.jpg")
.resize(50, 50)
.centerCrop()
.into(viewHolder.icon_1);
using request manager with glide :
RequestManager requestManager = Glide.with(a)
.applyDefaultRequestOptions(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.NONE))
.applyDefaultRequestOptions(RequestOptions.placeholderOf(R.drawable.ic_menu_camera));
requestManager
.applyDefaultRequestOptions(RequestOptions.skipMemoryCacheOf(true));
requestManager.load(pathToFile)
.into(viewHolder.icon_1);
background task method use :
String pathToFile = this.b.get(i).getThumnail();
DownloadImageWithURLTask downloadTask = new DownloadImageWithURLTask(viewHolder.icon_1);
downloadTask.execute(pathToFile);
public class DownloadImageWithURLTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageWithURLTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String pathToFile = urls[0];
Bitmap bitmap = null;
try {
InputStream in = new java.net.URL(pathToFile).openStream();
bitmap = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
Please help me how to solve this issue.
If you are load image in recyclerview, below code might help you out.
#Override
public void onBindViewHolder(final ViewHolder holder, int position)
{
Glide.with(this.context)
.load(urls.get(position))
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(holder.getImage());
}
for more full tutorial you can visit https://ledron.github.io/RecyclerView/
Dont pass MainActivity.this as context its always wrong..
try this
//in activity
Glide.with(this)
.load("https://pbs.twimg.com/profile_images/1123379185764917248/On9ZnfVh.png")
.into(imageView)
//in Fragments
Glide.with(view.context)
.load("url")
.into(imageView)
replace .load("url") and "imageView" with your own.
remove the below line in dependency
annotationProcessor 'com.github.bumptech.glide:compiler:4.10.0'
I am able to load your image url using glide:
implementation 'com.github.bumptech.glide:glide:4.9.0'
Glide.with(this#MainActivity)
.load("https://img.youtube.com/vi/EEX_XM6SxmY/mqdefault.jpg")
.placeholder(R.mipmap.ic_launcher)
.error(R.mipmap.ic_launcher)
.into(imageView)

Displaying an Image Downloaded from the Internet as Annotation - Using Picasso

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

ImageView refresh with 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;
}
});
}

TouchImageView zoom scaled to frame with Picasso

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

Improve the Volley NetworkImageView image quality?

I'm Using Volley NetworkImageView to load image from web.following method is to get ImageLoader.
public static ImageLoader getVolleyImageLoader(RequestQueue queue){
ImageLoader imageLoader = new ImageLoader(queue, new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap> mCache = new LruCache<String, Bitmap>(5);
public void putBitmap(String url, Bitmap bitmap) {
mCache.put(url, bitmap);
}
public Bitmap getBitmap(String url) {
return mCache.get(url);
}
});
return imageLoader;
}
this is layout widget
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/deal_thumb_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginLeft="#dimen/deals_image_left_margin" />
this is working fine.load image successfully. but the quality of the image is bad.size of the image is too small than the actual image.
How can I improve the quality of the image?
You have to include the volley source code into your project (as suggested in the Google IO 2014 Video)
Then open ImageLoader from the toolbox folder and change the configuration of the bitmap returning by the ImageRequest :
protected Request<Bitmap> makeImageRequest(String requestUrl, int maxWidth, int maxHeight,
ScaleType scaleType, final String cacheKey) {
return new ImageRequest(requestUrl, new Listener<Bitmap>() {
#Override
public void onResponse(Bitmap response) {
onGetImageSuccess(cacheKey, response);
}
}, maxWidth, maxHeight, scaleType, Config.RGB_565, new ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
onGetImageError(cacheKey, error);
}
});
}
Just change the Config.RGB_565 by Config.ARGB_8888 and you're done

Categories

Resources