Getting Image from URL (Java)
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
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();
}
}
Directly calling a URL to get an image may concern with major security issues.
You need to ensure that you have sufficient rights to access that resource.
However You can use ByteOutputStream
to read image file. This is an example (Its just an example, you need to do necessary changes as per your requirement.)
ByteArrayOutputStream bis = new ByteArrayOutputStream();
InputStream is = null;
try {
is = url.openStream ();
byte[] bytebuff = new byte[4096];
int n;
while ( (n = is.read(bytebuff)) > 0 ) {
bis.write(bytebuff, 0, n);
}
}
Try This:
//urlPath = address of your picture on internet
URL url = new URL("urlPath");
BufferedImage c = ImageIO.read(url);
ImageIcon image = new ImageIcon(c);
jXImageView1.setImage(image);