gpt4 book ai didi

java - Android 从 URL 加载到位图

转载 作者:IT老高 更新时间:2023-10-28 13:17:28 27 4
gpt4 key购买 nike

我有一个关于从网站加载图片的问题。我使用的代码是:

Display display = getWindowManager().getDefaultDisplay(); 
int width = display.getWidth();
int height = display.getHeight();
Bitmap bit=null;
try {
bit = BitmapFactory.decodeStream((InputStream)new URL("http://www.mac-wallpapers.com/bulkupload/wallpapers/Apple%20Wallpapers/apple-black-logo-wallpaper.jpg").getContent());
} catch (Exception e) {}
Bitmap sc = Bitmap.createScaledBitmap(bit,width,height,true);
canvas.drawBitmap(sc,0,0,null);

但是它总是返回一个空指针异常并且程序崩溃了。该 URL 有效,并且似乎对其他人都有效。我正在使用 2.3.1。

最佳答案

public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
// Log exception
return null;
}
}

关于java - Android 从 URL 加载到位图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8992964/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com