我想读下面的图片
但它显示IIOException,使其。
下面是代码:
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);
我想读下面的图片
但它显示IIOException,使其。
下面是代码:
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);
你得到一个HTTP 400
,因为有一个(错误请求)错误space
在您的网址。 如果你修复(前zoom
参数),你会得到一个HTTP 400
错误(未授权)。 也许你需要一些HTTP头,以确定您的下载作为一个公认的浏览器(使用“用户代理”标头)或附加认证参数。
对于用户代理实例中,然后使用ImageIO.read(InputStream的)使用连接的InputStream:
URLConnection connection = url.openConnection();
connection.setRequestProperty("User-Agent", "xxxxxx");
使用所需要的东西xxxxxx
此代码工作对我罚款。
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();
}
}
试试这个:
//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);
直接调用URL获得的图像可以与主要的安全问题关注。 你需要确保你有足够的权限来访问该资源。 但是你可以使用ByteOutputStream
读取图片文件。 这是一个例子(它只是一个例子,你需要做必要的修改,按您的要求。)
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);
}
}
试试这个:
class ImageComponent extends JComponent {
private final BufferedImage img;
public ImageComponent(URL url) throws IOException {
img = ImageIO.read(url);
setPreferredSize(new Dimension(img.getWidth(), img.getHeight()));
}
@Override protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 0, 0, img.getWidth(), img.getHeight(), this);
}
public static void main(String[] args) throws Exception {
final URL lenna =
new URL("http://bks6.books.google.ca/books?id=5VTBuvfZDyoC&printsec=frontcover&img=1& zoom=5&edge=curl&source=gbs_api");
final ImageComponent image = new ImageComponent(lenna);
JFrame frame = new JFrame("Test");
frame.add(new JScrollPane(image));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.setVisible(true);
}
}