我在服务器上有多个图像。我想要做的是我想从服务器检索这些图像并将其设置在 imageView 上。
我一直在从服务器获取 blob 类型图像,将其解码为字节数组,然后将其转换为位图图像。
我对如何从服务器获取位图图像感到困惑。
我经历过很多关于 SO 的问题
请任何人提供链接或代码帮助。
感谢您宝贵的时间。
我正在尝试,这里是代码:
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bitmap bitmap = DownloadImage("http://www.allindiaflorist.com/imgs/arrangemen4.jpg");
ImageView img = (ImageView) findViewById(R.id.img);
img.setImageBitmap(bitmap);
}
private InputStream OpenHttpConnection(String urlString)
throws IOException
{
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
}
catch (Exception ex)
{
throw new IOException("Error connecting");
}
return in;
}
private Bitmap DownloadImage(String URL)
{
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
BufferedInputStream bis = new BufferedInputStream(in, 8190);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
System.out.println("BAF= "+baf);
int current = 0;
while ((current = bis.read()) != -1)
{
baf.append((byte)current);
}
byte[] imageData = baf.toByteArray();
System.out.println("imageData= "+imageData);
bitmap =BitmapFactory.decodeByteArray(imageData, 0, imageData.length);
in.close();
}
catch (IOException e1)
{
e1.printStackTrace();
}
return bitmap;
}
}
这将返回图像,但我使用的 URL 包含图像名称。如果我有更多图像并且我想在我的应用程序加载时检索所有图像怎么办。