我有一个 android 应用程序,它向服务器请求图像,并且应该在 ImageView
中显示该请求图像。图像存储在图像文件夹中,其路径存储在 MySQL
数据库中。我正在使用 php
作为服务器端脚本。 Android 应用向 image.php
文件请求特定图像,该文件从数据库中获取请求图像所在文件夹的路径,并以 json 格式返回。
现在我的问题是:
仅此路径是否足以在 Android 应用程序中显示图像?还是应用程序应该先下载该图像才能显示它?
我在 SO 的某处看到您可以将图像编码为字符串并将该字符串返回给 android 应用程序并将该字符串解码回图像?这是一种有效的方法吗?
这更像是一个一般性问题,因此我们将不胜感激。
最佳答案
- 是的,您必须下载图像才能显示它,但您不必永远存储它,您可以使用
BitmapFactory
解码ByteArray
获取图片的Bitmap
。或者使用像 Picasso 这样的库“缓存”您的图像,就像在另一个答案中建议的那样。
This question讨论了许多关于如何使用一些库在 Android 上下载图像的方法。或者您可以尝试原生方法,如下所示:
public class LoginActivity extends Activity implements OnClickListener {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
this.findViewById(R.id.userinfo_submit).setOnClickListener(this);
// Verify Code
LinearLayout view = (LinearLayout) findViewById(R.id.txt_verify_code);
view.addView(new VerifyCodeView(this));
// show The Image
new DownloadImageTask((ImageView) findViewById(R.id.imageView1))
.execute(“http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png”);
}
public void onClick(View v) {
startActivity(new Intent(this, IndexActivity.class));
finish();
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String… urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e(“Error”, e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
此代码取自 here .
- 您可以在您的服务器上将您的图像编码为 Base64
String
并稍后在您的 Android 上对其进行解码。
要对其进行解码,请尝试以下操作:
byte[] data = Base64.decode(base64Image, Base64.DEFAULT);
Bitmap bm;
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inMutable = true;
bm = BitmapFactory.decodeByteArray(data, 0, data.length, opt);
// Now do whatever you want with the Bitmap.
您可以查看 Bitmap
类的文档 here .
但老实说,您只是在流程中添加了另一个步骤,并因此浪费了处理器周期。我想按原样下载图像效率更高。
有关 Base64
类的更多信息,请参阅 docs .
关于php - 在android中从服务器接收图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31681061/