JavaでURLから画像をダウンロードの方法
Java では、URL クラスと HttpURLConnection クラスを使用して画像をダウンロードできます。簡単なサンプルは次のとおりです。
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class ImageDownloader {
public static void main(String[] args) {
String imageUrl = "http://example.com/image.jpg";
String destinationPath = "C:/path/to/save/image.jpg";
try {
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
InputStream inputStream = connection.getInputStream();
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
FileOutputStream fileOutputStream = new FileOutputStream(destinationPath);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = bufferedInputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, bytesRead);
}
fileOutputStream.close();
bufferedInputStream.close();
System.out.println("Image downloaded successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
imageUrlをダウンロードしたい画像のURLに、destinationPathを画像を保存したいパスに置き換えて実行すれば、画像がダウンロードできます。