Java image resource url

How to download image from from url in java?

I have been trying to download an image from url via java.
I tried to solve it with many ways but I didn’t succeed. I’m writing my ways hoping someone will find where it went wrong: With the first and second ways I get the following error while I’m trying to open the image:

URL url = new URL("http://www.avajava.com/images/avajavalogo.jpg"); InputStream in = url.openStream(); Files.copy(in, Paths.get("someFile.jpg"), StandardCopyOption.REPLACE_EXISTING); in.close(); 
File f= new File("c:\\image.jpg"); URL myUrl = new URL("http://www.avajava.com/images/avajavalogo.jpg"); FileUtils.copyURLToFile(myUrl, f); 

With way 3 i get Exception in thread «main» java.lang.IllegalArgumentException: image == null! Third way:

URL url = new URL("http://www.avajava.com/images/avajavalogo.jpg"); BufferedImage img = ImageIO.read(url); File file = new File("downloaded.jpg"); ImageIO.write(img, "jpg", file); 

I really need your help. I have been trying to solve it a long time ago without success. Thanks in advance.

Please attach your downloaded file from the 1st case here so we can verify if it’s really damaged. Also I’d try downloading it via other means and doing diff on that and java-downloaded one to see what’s the dfiference

An image is only a binary content nothing more. Knowing that the first will work with any type of content (binary or not), it will work with images too

the only remark I could make is to use a try-with-resources statement to close your stream whatever happens, like this answer stackoverflow.com/a/32472138/1997376

2 Answers 2

You have to specify the full location for the destination file in way 3:

URL url = new URL("http://www.avajava.com/images/avajavalogo.jpg"); BufferedImage img = ImageIO.read(url); File file = new File("D:\\image\\downloaded.jpg"); ImageIO.write(img, "jpg", file); 

When this happens usually the image you are trying to download is located inside a placeholder. Placeholders are used to give the image some nice black background in all browsers or any kind of valuable methods..

Try to open one of your downloaded images with small size with any text editor. You will probably be surprised to see an HTML code inside your supposed image. This HTML code will have a few lines, usually a background color tag and the image real URL. This is the URL that you have to include in your code in order to download the full image.

This could be an example of the avajavalogo.jpg file that you are actually downloading:

   
Click on image to close it.

If you try to open this file with an image editor, it will throw an error (wrong headers, bad format, etc) and the image will not be opened. It is not the case of the image you have showed in your question, but it could be the case of the images you are actually trying to download.

Читайте также:  Вывести ascii код символа python

Apart from that, the methods exposed are valid.

Источник

how to get an uri of an image resource in android

when i try to send image as email attachment it is sending the file but without .jpg extension. So the image isn’t valid in the receipients pc.

@hemanthkumar See this answer as a reference : stackoverflow.com/a/8476930/62921 He explain that there is no drawable folder except on your machine. That’s why it uses IDs and that your path.toString() doesn’t work.

This does not work for me. I get ActivityNotFoundException. (android.content.ActivityNotFoundException: No Activity found to handle Intent < act=android.intent.action.VIEW dat=android.resource://com.mypackage.myapp/2130837582 >. LG E400 Android 2.3.6.

Here is a clean solution which fully leverages the android.net.Uri class via its Builder pattern, avoiding repeated composition and decomposition of the URI string, without relying on hard-coded strings or ad hoc ideas about URI syntax.

Resources resources = context.getResources(); Uri uri = new Uri.Builder() .scheme(ContentResolver.SCHEME_ANDROID_RESOURCE) .authority(resources.getResourcePackageName(resourceId)) .appendPath(resources.getResourceTypeName(resourceId)) .appendPath(resources.getResourceEntryName(resourceId)) .build(); 

Minimally more elegant with Kotlin:

fun Context.resourceUri(resourceId: Int): Uri = with(resources)
@Composable fun rememberResourceUri(resourceId: Int): Uri < val context = LocalContext.current return remember(resourceId) < with(context.resources) < Uri.Builder() .scheme(ContentResolver.SCHEME_ANDROID_RESOURCE) .authority(getResourcePackageName(resourceId)) .appendPath(getResourceTypeName(resourceId)) .appendPath(getResourceEntryName(resourceId)) .build() >> > 

Источник

Getting Image from URL (Java)

enter image description here

I am trying to read the following image But it is showing IIOException. Here is the code:

Image image = null; URL url = new URL("http://bks6.books.google.ca/books?id=5VTBuvfZDyoC&printsec=frontcover&img=1& zoom=5&edge=curl&source=gbs_api"); image = ImageIO.read(url); jXImageView1.setImage(image); 

6 Answers 6

This code worked fine for me.

 import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; public class SaveImageFromUrl < public static void main(String[] args) throws Exception < String imageUrl = "http://www.avajava.com/images/avajavalogo.jpg"; String destinationFile = "image.jpg"; saveImage(imageUrl, destinationFile); >public static void saveImage(String imageUrl, String destinationFile) throws IOException < URL url = new URL(imageUrl); InputStream is = url.openStream(); OutputStream os = new FileOutputStream(destinationFile); byte[] b = new byte[2048]; int length; while ((length = is.read(b)) != -1) < os.write(b, 0, length); >is.close(); os.close(); > > 

Hi. Is there a api that would return the image if I provide a website link? stackoverflow.com/questions/38612896/…

Читайте также:  Python encode json to utf 8

You are getting an HTTP 400 (Bad Request) error because there is a space in your URL. If you fix it (before the zoom parameter), you will get an HTTP 401 error (Unauthorized). Maybe you need some HTTP header to identify your download as a recognised browser (use the «User-Agent» header) or additional authentication parameter.

For the User-Agent example, then use the ImageIO.read(InputStream) using the connection inputstream:

URLConnection connection = url.openConnection(); connection.setRequestProperty("User-Agent", "xxxxxx"); 

Use whatever needed for xxxxxx

I have the same problem but when I add Image image = ImageIO.read(url) i get an error — Cannot resolve symbol IO

Источник

How can I fetch image format from a URL in Java?

I have an image that I fetch from a url that has no extension(jpg, gif,png, etc). I have no problem downloading the image.

BufferedImage image = null; URL url = new URL(link); image = ImageIO.read(url); 

However, I wanted to know the extension of the file before saving to disk. I tried the following and ImageIO.createImageInputStream(image); is always returning null.

ImageInputStream iis = ImageIO.createImageInputStream(image); //where image is BufferImage but it is always returning null. while (imageReaders.hasNext())

It’s ImageIO.createImageInputStream(url) (i.e. not image ). Don’t read the image, you don’t need to, if you only want to save to disk.

2 Answers 2

Once you create a java.awt.Image, there is no format. It’s not a PNG, it’s not a JPEG, it’s just a Java Image. So you cannot get the image format from your Image object.

You need to get it from the URL. The most reliable way is to check the URL’s content type, then get the extension from the ImageIO provider:

URL url = new URL(link); URLConnection conn = url.openConnection(); String contentType = conn.getContentType(); String suffix = null; Iterator readers = ImageIO.getImageReadersByMIMEType(contentType); while (suffix == null && readers.hasNext()) < ImageReaderSpi provider = readers.next().getOriginatingProvider(); if (provider != null) < String[] suffixes = provider.getFileSuffixes(); if (suffixes != null) < suffix = suffixes[0]; >> > 

You can also save the URL to a temporary file, so you can use Files.probeContentType on it:

URL url = new URL(link); Path imageFile = Files.createTempFile("image", null); try (InputStream stream = url.openStream()) < Files.copy(stream, imageFile, StandardCopyOption.REPLACE_EXISTING); >image = ImageIO.read(imageFile.toFile()); String contentType = Files.probeContentType(imageFile); Files.delete(imageFile); 

But you’ll still need ImageIO providers to get an extension from a MIME type.

Thank you so much @VGR. This is what I was looking for. One quick question though: String contentType = conn.getContentType(); This is already giving me image/png. Isn’t it enough to stop at this stage?

Читайте также:  Div box css html

No. The subtype (the part after the / ) is not guaranteed to be the same as the extension. Consider «image/jpeg» and «image/svg+xml».

Also, some servers are lying about content types (i.e. are misconfigured, or relies on file extension which may be incorrect). So you can’t blindly trust the content type. Looking at the actual payload, like Files.probeContentType(..) does is safer.

In Java 7+ you can now just use Files.probeContentType(path).

---------- public static String probeContentType(Path path) throws IOException 

Probes the content type of a file.

This method uses the installed FileTypeDetector implementations to probe the given file to determine its content type. Each file type detector’s probeContentType is invoked, in turn, to probe the file type. If the file is recognized then the content type is returned. If the file is not recognized by any of the installed file type detectors then a system-default file type detector is invoked to guess the content type.

A given invocation of the Java virtual machine maintains a system-wide list of file type detectors. Installed file type detectors are loaded using the service-provider loading facility defined by the ServiceLoader class. Installed file type detectors are loaded using the system class loader. If the system class loader cannot be found then the extension class loader is used; If the extension class loader cannot be found then the bootstrap class loader is used. File type detectors are typically installed by placing them in a JAR file on the application class path or in the extension directory, the JAR file contains a provider-configuration file named java.nio.file.spi.FileTypeDetector in the resource directory META-INF/services, and the file lists one or more fully-qualified names of concrete subclass of FileTypeDetector that have a zero argument constructor. If the process of locating or instantiating the installed file type detectors fails then an unspecified error is thrown. The ordering that installed providers are located is implementation specific.

The return value of this method is the string form of the value of a Multipurpose Internet Mail Extension (MIME) content type as defined by RFC 2045: Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies. The string is guaranteed to be parsable according to the grammar in the RFC.

Источник

Оцените статью