gpt4 book ai didi

java - 如何在android中显示bmp图像

转载 作者:太空宇宙 更新时间:2023-11-03 13:30:37 26 4
gpt4 key购买 nike

我是 java 和 android 开发的新手。我试图找到这个问题的答案,但似乎很明显,所以没有人问这个..我用这个例子来显示图像:

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String str="http://logproj.500mb.net/image.php?id=8";
ImageView imView;
imView = (ImageView)findViewById(R.id.image);
try{
url = new URL(str);
}
catch(MalformedURLException e)
{
e.printStackTrace();
}
try{
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setDoInput(true);

conn.connect();
int length = conn.getContentLength();

int[] bitmapData =new int[length];
byte[] bitmapData2 =new byte[length];

InputStream is = conn.getInputStream();

bmp = BitmapFactory.decodeStream(is);
imView.setImageBitmap(bmp);
} catch (IOException e)
{
e.printStackTrace();
}

}

它适用于 jpg 图像,但我的图像是 bmp 并且应用程序崩溃或“意外停止”。

我希望你能帮助解决这个问题。提前致谢。

最佳答案

使用 apaches 网络客户端试试这个。这应该工作。让我知道。

public static Bitmap decodeFromUrl(HttpClient client, URL url, Config bitmapCOnfig)
{
HttpResponse response=null;
Bitmap b=null;
InputStream instream=null;

BitmapFactory.Options decodeOptions = new BitmapFactory.Options();
decodeOptions.inPreferredConfig = bitmapCOnfig;
try
{
HttpGet request = new HttpGet(url.toURI());
response = client.execute(request);
if (response.getStatusLine().getStatusCode() != 200)
{
Log.d("Bad response on " + url.toString());
Log.d("http response: " + response.getStatusLine().toString());
return null;
}
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(response.getEntity());
instream = bufHttpEntity.getContent();

return BitmapFactory.decodeStream(instream, null, decodeOptions);
}
catch (Exception ex)
{
Log.d("error decoding bitmap from:" + url, ex);
if (response != null)
{
Log.d("http status: " + response.getStatusLine().getStatusCode());
}
return null;
}
finally
{
if (instream != null)
{
try {
instream.close();
} catch (IOException e) {
Log.d("error closing stream", e);
}
}
}
}

不要忘记从异步任务中调用此函数。

关于java - 如何在android中显示bmp图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13792217/

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