How to download Image from URL in java?
DownloadImage.java
/* Code From Learnoset - Learn Code Online Android App.*/
/*Download Learnoset App from PlayStore to learn coding*/
/*How to download Image from URL in java?*/
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
public class DownloadImage {
public static void main(String[] args) {
// Url of Image
String imageUrl = "https://homepages.cae.wisc.edu/~ece533/images/airplane.png";
String imageFilePath = "F:\\downloaded.jpg";
InputStream inputStream = null; //Declare InputStream to read data from URL
OutputStream outputStream = null; //Declare OutputStream to save Image to Local Memory
try {
URL url = new URL(imageUrl); // Create an Object of URL class and pass imageUrl in Constructor
inputStream = url.openStream(); // Open InputStream from url to read image filed
outputStream = new FileOutputStream(imageFilePath); // create outputStream and pass image file path to save image
byte[] buffer = new byte[2048]; // create byte array which hold 2048 bytes from inputStream
int length;
/* Create a while loop until every byte from inputStream will be written to outputStream.
inputStream.read(buffer) will return -1 when its end of image file*/
while ((length = inputStream.read(buffer)) != -1) {
// write buffer of 2048 bytes from inputStream to outputStream while there is no bytes left in inputStream
outputStream.write(buffer, 0, length);
}
} catch (MalformedURLException e) {
System.out.println("MalformedURLException :- " + e.getMessage());
} catch (FileNotFoundException e) {
System.out.println("FileNotFoundException :- " + e.getMessage());
} catch (IOException e) {
System.out.println("IOException :- " + e.getMessage());
} finally {
try {
inputStream.close();
outputStream.close();
} catch (IOException e) {
System.out.println("Finally IOException :- " + e.getMessage());
}
}
}
}
Projects with Source Code + Video Tutorials
You can download our Java and Android Studio Projects with Source Code and Video Tutorials.
Login and Register screen with OTP Verification Material UI design
Settings and Profile page UI design in Android Studio with Example and Source Code
Login & Register Screen UI Design - 01
If you have any Questions or Queries
You can mail us at info.learnoset@gmail.com
Follow us to learn Coding and get in touch with new Technologies.