Load Image from Url

Load image from url

URL url = new URL("http://image10.bizrate-images.com/resize?sq=60&uid=2216744464");
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
imageView.setImageBitmap(bmp);

How to load an ImageView by URL in Android?

Anyway people ask my comment to post it as answer. i am posting.

URL newurl = new URL(photo_url_str); 
mIcon_val = BitmapFactory.decodeStream(newurl.openConnection().getInputStream());
profile_photo.setImageBitmap(mIcon_val);

How to display Image from a url in SwiftUI

iOS 15 update:

you can use asyncImage in this way:
AsyncImage(url: URL(string: "https://your_image_url_address"))

more info on Apple developers document:
AsyncImage

Using ObservableObject (Before iOS 15)

first you need to fetch image from url :

class ImageLoader: ObservableObject {
var didChange = PassthroughSubject<Data, Never>()
var data = Data() {
didSet {
didChange.send(data)
}
}

init(urlString:String) {
guard let url = URL(string: urlString) else { return }
let task = URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data else { return }
DispatchQueue.main.async {
self.data = data
}
}
task.resume()
}
}

you can put this as a part of your Webservice class function too.

then in your ContentView struct you can set @State image in this way :

struct ImageView: View {
@ObservedObject var imageLoader:ImageLoader
@State var image:UIImage = UIImage()

init(withURL url:String) {
imageLoader = ImageLoader(urlString:url)
}

var body: some View {

Image(uiImage: image)
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width:100, height:100)
.onReceive(imageLoader.didChange) { data in
self.image = UIImage(data: data) ?? UIImage()
}
}
}

Also, this tutorial is a good reference if you need more

How to load Image into ImageView from Url using Glide v4.0.0RC1

If you are using Glide v4.0.0-RC1 then you need to use RequestOptions to add the placeholder, error image and other option. Here is an working example

RequestOptions options = new RequestOptions()
.centerCrop()
.placeholder(R.mipmap.ic_launcher_round)
.error(R.mipmap.ic_launcher_round);



Glide.with(this).load(image_url).apply(options).into(imageView);

How to load image from URL that is in database

you can load an image from URL by using Glide:

Import dependency

implementation 'com.github.bumptech.glide:glide:4.11.0'

        Glide
.with(context)
.load("URL placed here")
.centerCrop()
.placeholder(R.drawable.placeholder)
.into(imageview)

Load image from Url without third-party

I solved it with this code:

@BindingAdapter("imageUrl")
fun ImageView.bindImage(imgUrl: String?) {

if(this.drawable == null) {

imgUrl?.let {
val imgUri = imgUrl.toUri().buildUpon().scheme("https").build().toString()


val uiHandler = Handler(Looper.getMainLooper())
thread(start = true) {
val bitmap = downloadBitmap(imgUri)
uiHandler.post {
this.setImageBitmap(bitmap)
}
}
}
}

}

fun downloadBitmap(imageUrl: String): Bitmap? {
return try {
val conn = URL(imageUrl).openConnection()
conn.connect()
val inputStream = conn.getInputStream()
val bitmap = BitmapFactory.decodeStream(inputStream)
inputStream.close()
bitmap
} catch (e: Exception) {
Log.e(ContentValues.TAG, "Exception $e")
null
}
}
  1. Check if it's not loaded yet to avoid more than one loaded.
  2. Add HTTPS to the URL.
  3. Create a thread to open an input stream connection and get the image bitmap.
  4. Create a handler to return to main thread and set image bitmap.

Load image from URL and default image on error

You can use the errorProperty and exceptionProperty to check the error status of the image:

import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.image.Image;
import javafx.stage.Stage;

public class ImageTest extends Application {

public static void main(String[] args) {
launch(args) ;
}

@Override
public void start(Stage primaryStage) {
String[] urls = new String[]{
"https://www.wbkidsgo.com/Portals/1/Content/Hero/HeroBugsCarrot/Source/Default/WB_LT_HeroImage_Bugs_v1.png",
"https://www.wbkidsgo.com/Portalss/1/Content/Hero/HeroBugsCarrot/Source/Default/WB_LT_HeroImage_Bugs_v1.png"
} ;

for (String url : urls) {
Image image = new Image(url);
if (image.isError()) {
System.out.println("Error loading image from "+url);
// if you need more details
// image.getException().printStackTrace();
} else {
System.out.println("Successfully loaded image from " + url);
}
}
Platform.exit();
}

}

Which gives the following output:

Successfully loaded image from https://www.wbkidsgo.com/Portals/1/Content/Hero/HeroBugsCarrot/Source/Default/WB_LT_HeroImage_Bugs_v1.png
Error loading image from https://www.wbkidsgo.com/Portalss/1/Content/Hero/HeroBugsCarrot/Source/Default/WB_LT_HeroImage_Bugs_v1.png

What's the fastest way to read images from urls?

Assuming you are actually using keras and that this image.load_img is the method you are calling, it would call a function which should ultimately be PIL.Image.open. In the documentation for PIL.image.open, the first argument fp could be a string filename (which is what you are currently passing), or a stream-like object that implements read, seek, and tell. While the object returned by urllib.request.urlopen does provide all three methods, it does not implement seek at all, so it cannot be used directly. However, the entire buffer can be read into an BytesIO object which does implement seek, so it should be usable. Putting this together, your loadImage function may be reduced to something like the following:

from io import BytesIO

def loadImage(URL):
with urllib.request.urlopen(URL) as url:
img = image.load_img(BytesIO(url.read()), target_size=(125, 125))

return image.img_to_array(img)

This keeps the images downloaded fully in memory.

Picasso does not load bigger images from url

Apparently the solution was to use Picasso.get().load(displayImageUrl) instead of Target. There was no need for resizing the image. The question why the Target fails sometimes is still unanswered though.

How to load image from URL in Jetpack Compose?

You can use Coil for compose:

  • https://coil-kt.github.io/coil/compose/

Add the dependency:

implementation("io.coil-kt:coil-compose:2.0.0-rc01")

and use it like this:

Image(
painter = rememberAsyncImagePainter("https://www.example.com/image.jpg"),
contentDescription = null,
modifier = Modifier.size(128.dp)
)


Related Topics



Leave a reply



Submit