我总是在调用此方法时得到响应NULL但是如果假设我在浏览器中运行它会显示图像.public Bitmap getBitmapFromURL(String src){ 位图bmImg; URL myFileUrl = null;
try {
myFileUrl = new URL("http://www.russiawear.com/components/com_virtuemart/shop_image/product/youth_russia_usa_4e2f7f78b543c.jpg");
HttpURLConnection conn = (HttpURLConnection) myFileUrl
.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
BitmapFactory.Options options = new BitmapFactory.Options();
bmImg = BitmapFactory.decodeStream(is, null, options);
return bmImg;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}`
什么可能有问题?
答案 0 :(得分:0)
我只是使用它,在我的情况下它的工作正常。
URL newurl;
try
{
newurl = new URL("http://www.russiawear.com/components/com_virtuemart/shop_image/product/youth_russia_usa_4e2f7f78b543c.jpg");
bitmap = BitmapFactory.decodeStream(newurl.openConnection().getInputStream());
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
<强>更新强>
来自网址的下载文件代码,
try
{
URL url = new URL("http://www.russiawear.com/components/com_virtuemart/shop_image/product/youth_russia_usa_4e2f7f78b543c.jpg"); //you can write here any link
File file = new File("/sdcard/temp.jpg");
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1)
{
baf.append((byte) current);
}
/* Convert the Bytes read to a String. */
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
}
catch (IOException e)
{
Log.d("ImageManager", "Error: " + e);
}
然后使用文件
创建位图bitmap = BitmapFactory.decodeFile("/sdcard/temp.jpg");
答案 1 :(得分:0)
private Bitmap loadBitmap() {
Bitmap bmQR = null;
InputStream inputStream = null;
try {
inputStream = OpenHttpConnection(url);
bmQR = BitmapFactory.decodeStream(inputStream);
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bmQR;
}
private InputStream OpenHttpConnection(String strURL) throws IOException {
InputStream is = null;
URL url = new URL(strURL);
URLConnection urlConnection = url.openConnection();
try {
HttpURLConnection httpConn = (HttpURLConnection) urlConnection;
httpConn.setRequestMethod("GET");
httpConn.connect();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
is = httpConn.getInputStream();
}
} catch (Exception ex) {
}
return is;
}