I need to set image to my image view
For this reason I use Picasso library
Here is approach how I do this
File image = new File("file:" + path);
Picasso.with(context)
.load(image)
.placeholder(R.drawable.progress_animation)
.error(R.drawable.image_error_404)
.into(iv);
and also I tried the same without prefix file: like here
File image = new File(path);
Picasso.with(context)
.load(image)
.placeholder(R.drawable.progress_animation)
.error(R.drawable.image_error_404)
.into(iv);
But all the time I got image from .error() ,
There is a path with file: prefix - "file:/storage/emulated/0/Android/data/com.fittingroom.newtimezone/files/default/AvatarPackage/DEFAULT_MY_AVATAR/pose1.jpeg"
and there is path witout file: prefix - "/storage/emulated/0/Android/data/com.fittingroom.newtimezone/files/default/AvatarPackage/DEFAULT_MY_AVATAR/pose1.jpeg"
Anyway I got no result
Why picasso doesn't want to set my image
What am I doing wrong?
Your path prefix is incorrect: use file:/// instead of file:
Thanks #CommonsWare I solve my issue such way
.fit()
.centerInside()
And here is my implementation
File image = new File(path);
Picasso picasso = new Picasso.Builder(context)
.listener(new Picasso.Listener() {
#Override public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) {
Logger.logError("ERROR Download image: ", exception, context);
}
}).build();
picasso
.load(image)
.fit()
.centerInside()
.placeholder(R.drawable.progress_animation)
.error(R.drawable.image_error_404)
.into(iv, new Callback() {
#Override public void onSuccess() {
Logger.logGeneral("image downloaded");
}
#Override public void onError() {
Logger.logGeneral("onError image downloaded");
}
});
Related
I have an activity that need to load multiples images and resize them so that they fit screen width.
I try to load the images into this.frameHolder which is a LinearLayout inside a NestedScrollView and do match the screen width.
The code below is working but make the application very slow as soon as there is more than few images.
public void displayImages(List<ImageContent> images) {
for(ImageContent img:images) {
//Create an new view for image
ImageView imgView = new ImageView(this);
this.frameHolder.addView(imgView);
//Create a client with custom header for this image
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(chain -> {
Request.Builder newRequest = chain.request().newBuilder();
newRequest.addHeader(img.getHeaderKey(), img.getHeaderValue());
return chain.proceed(newRequest.build());
}).build();
//Create a picasso instance for this client
Picasso.Builder builder = new Picasso.Builder(this).downloader(new OkHttp3Downloader(client));
Picasso pic = builder.build();
//Load and resize the image to fit screen width
pic.load(img.getUrlContentData()).resize(frameHolder.getWidth(), 0).into(imgView);
}
}
How can I load multiple images and make them fit the screen width, without degrading performance too much ? I'm open to other solution than Picasso if that make it possible.
I ended giving up on using a library, as #Qasim Malik suggested I've tried Glide and Fresco as alternatives, but I still got similar issues.
So since I wasn't able to do it with a library, I did it myself by handling the request and image resizing directly :
private final static OkHttpClient client = new OkHttpClient();
public void displayImages(List<ImageContent> images) {
for(ImageContent img:images) {
ImageView imgView = new ImageView(this);
this.frameHolder.addView(imgView);
Request.Builder requestBuilder = new Request.Builder()
.addHeader(img.getHeaderKey(), img.getHeaderValue())
.url(content.getUrlContentData());
client.newCall(requestBuilder.build()).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
loadFailed();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
Bitmap bitmap = BitmapFactory.decodeStream(response.body().byteStream());
float widthInitial = bitmap.getWidth() ;
float heightInitial = bitmap.getHeight() ;
Bitmap resizedImage = Bitmap.createScaledBitmap(bitmap, frameHolder.getWidth(), Math.round(frameHolder.getWidth() * (heightInitial / widthInitial)), true);
imgView.setImageBitmap(resizedImage);
}
});
}
}
This work fine, and there are no more performance issues, but I'm still unsure of why the libraries are so slow at it...
I am using Glide to load images. Currently, when the images are already loaded, they are saved into a cache and then fetched from it when asked for the same image again. But when the cache gets filled, does Glide delete the old files? If so, how do I know when it has done so and to which image?
Glide.with(context)
.asBitmap()
.load(new GlideUrl(url, new LazyHeaders.Builder()
.addHeader("Authorization", "Bearer " + getAuthorizationToken())
.build()))
.into(new CustomTarget<Bitmap>(width, height) {
#Override
public void onResourceReady(#NonNull Bitmap resource, #Nullable Transition<? super Bitmap> transition) {
imageView.setImageBitmap(resource);
eventEmitter.onPageRender(position);
}
#Override
public void onLoadCleared(#Nullable Drawable placeholder) {
}
});
I tried all examples both from the docs and from online help, but I can't get a simple image I have in the storage to display on an image view.
assuming I have pictures in the storage in a folder called pictures so photo1.jpg is stored in the reference:
StorageReference storageReference = FirebaseStorage.getInstance().getReference();
StorageReference photoReference= storageReference.child("pictures/photo1.jpg");
But how do I set it and replace the contents with an existing image view that I find by id:
ImageView photoView= (ImageView) findViewById(R.id.photo_view);
I keep getting failure on the listener to get Uri:
storageReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
profileImage.setImageURI(uri);
Log.d("Test"," Success!");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Log.d("Test"," Failed!");
}
});
Using below code you can set image on ImageView:
StorageReference storageReference = FirebaseStorage.getInstance().getReference();
StorageReference photoReference= storageReference.child("pictures/photo1.jpg");
final long ONE_MEGABYTE = 1024 * 1024;
photoReference.getBytes(ONE_MEGABYTE).addOnSuccessListener(new OnSuccessListener<byte[]>() {
#Override
public void onSuccess(byte[] bytes) {
Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
imageView.setImageBitmap(bmp);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Toast.makeText(getApplicationContext(), "No Such file or Path found!!", Toast.LENGTH_LONG).show();
}
});
You can use the Uri as well, for that you need to save the byte array to a file. Use below code for the same:
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "test.jpg");
f.createNewFile();
//write the bytes in file
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
// remember close de FileOutput
fo.close();
There may be something going wrong with the uri you have retrieved from the Firebase Storage, try putting it on log, like this:
Log.d("uri:",uri.toString());
This may give you a hint, what is going wrong with retrieving the value. If you choose to use Glide or Picasso, then do refer their GitHub pages from the links above, and see what you need.
Using Glide and Picasso both is simple, and here's an example of how to use Glide to store the images in your imageView.
// Reference to an image file in Cloud Storage
StorageReference storageReference = = FirebaseStorage.getInstance().getReference().child("yourImageReferencePath");
ImageView image = (ImageView)findViewById(R.id.imageView);
// Load the image using Glide
Glide.with(this /* context */)
.using(new FirebaseImageLoader())
.load(storageReference)
.into(image );
If you don't want to use any external library and want to retrieve the image, then do refer this answer, it might help.
Try to get the download URL of the image that you have uploaded in the database and use Picasso or GLIDE library to load it into the imageview you desire.
I use two libraries simultaneously to work with photos.
1.implementation 'com.github.bumptech.glide:glide:4.7.1'
annotationProcessor 'com.github.bumptech.glide:compiler:4.7.1'
(https://github.com/bumptech/glide)
2. compile 'co.gofynd.library:gravity-view:1.0'
(https://github.com/gofynd/gravity-view)
I want to get a photo from the Internet with the Glide library then use the
gravity library
But the library's inputs are imageview and int drawable.
I can not get the int drawable input
my codes for the gravity library:
private void setGravityMotion()
{
gravityView = GravityView.getInstance(this);
if (!gravityView.deviceSupported())
{
return;
} else
{
gravityView.setImage(imageView, R.drawable.background)
.center();
Toast.makeText(this, "ok", Toast.LENGTH_SHORT).show();
}
}
What should I do instead of R.drawable.background?
The library you are using supports two types of images
The resource int
Bitmap image
You are using the first type which cannot be used with Glide. Instead create a bitmap using the Glide library then load it in the library.
Your code will look like this
Glide
.with(getApplicationContext())
.load("https://www.google.es/images/srpr/logo11w.png")
.asBitmap()
.into(new SimpleTarget<Bitmap>(100,100) {
#Override
public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) {
gravityView.setImage(imageView, resource)
}
});
I believe Glide 4.0 has a different way to get bitmap but it will still work
Please check screen shot of drawable you need to use.
private void setGravityMotion()
{
gravityView = GravityView.getInstance(this);
if (!gravityView.deviceSupported())
{
return;
} else
{
gravityView.setImage(imageView, R.drawable.ic_3d)
.center();
Toast.makeText(this, "ok", Toast.LENGTH_SHORT).show();
}
}
You can use probably like this:
ViewTarget<ImageView, Bitmap> viewTarget = Glide.with(activity)
.asBitmap()
.load("URL")
.into(imageView);
Drawable drawable = viewTarget.getView().getDrawable(); // Declare according your scope
private void setGravityMotion() {
gravityView = GravityView.getInstance(this);
if (!gravityView.deviceSupported())
{
return;
} else
{
gravityView.setImage(imageView, drawable/*Place here*/)
.center();
Toast.makeText(this, "ok", Toast.LENGTH_SHORT).show();
}
}
I have not tested it, Hope it works.
I have a fragment that i'm calling again and again it has Picasso in it to load images from url when I pop back same fragment with different url to load image from, the previous image shown until new image loaded, how can i solve this problem, here is my code:
Picasso.with(context)
.load(url)
.networkPolicy(NetworkPolicy.NO_CACHE)
.into(ivParallex, new com.squareup.picasso.Callback() {
#Override
public void onSuccess() {
getProductDetail(productId);
} else {
}
#Override
public void onError() {
}
});