import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
public class OpenAIWebClientExample {
public static void main(String[] args) {
String imageUrl = "https://light-show.oss-cn-guangzhou.aliyuncs.com/image/20231129/img-r9VLTf57kQRzGlE1m7pTdMOD.png";
try {
byte[] imageData = downloadImage(imageUrl);
// Now you have the image data as byte[]
System.out.println("Downloaded " + imageData.length + " bytes");
} catch (IOException e) {
e.printStackTrace();
}
}
public static byte[] downloadImage(String imageUrl) throws IOException {
URL url = new URL(imageUrl);
try (InputStream in = url.openStream();
ByteArrayOutputStream buffer = new ByteArrayOutputStream()) {
int bytesRead;
byte[] data = new byte[1024];
while ((bytesRead = in.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, bytesRead);
}
return buffer.toByteArray();
}
}
}
在这个示例中,downloadImage
方法将远程图片的内容读取到一个 ByteArrayOutputStream
中,最后通过 toByteArray
方法获取 byte[]
。你可以根据需要调整代码。