大家好。
我正在尝试编写一个Android应用程序,该应用程序应从mysql数据库中检索到一个Blob,并将其转换为Android上的imageview。
我可以成功地将图像加载到Web服务器(XAMPP),将其编码为blob并将其存储在sql表中。
向大家致意!
公共类RequestHandler {
public String sendGetRequest(String uri) {
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String result;
StringBuilder sb = new StringBuilder();
while((result = bufferedReader.readLine())!=null){
sb.append(result);
}
return sb.toString();
} catch (Exception e) {
return null;
}
}
这里是检索图像的代码:
公共类ViewImage扩展了AppCompatActivity实现的View.OnClickListener {
private RequestHandler requestHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.download);
RequestHandler rh = new RequestHandler();
buttonGetImage.setOnClickListener(this); }
private void getImage() {
String id = editTextId.getText().toString().trim();
class GetImage extends AsyncTask<String,Void,Bitmap>{
ProgressDialog loading;
RequestHandler rh = new RequestHandler();
@Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(ViewImage.this, "Uok..", null,true,true);
}
@Override
protected void onPostExecute(Bitmap b) {
super.onPostExecute(b);
loading.dismiss();
imageView.setImageBitmap(b);
}
@Override
protected Bitmap doInBackground(String... params) {
String id = params[0];
String add = "http://192.168.1.121:8080/getImage.php?id="+id;
URL url = null;
Bitmap image = null;
try {
url = new URL(add);
rh.sendGetRequest(add);
image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return image;
}
}
GetImage gi = new GetImage();
gi.execute(id);
}
@Override
public void onClick(View v) {
getImage();
}
}
此处是php脚本:
if($_SERVER['REQUEST_METHOD']=='GET'){
$id = $_GET['id'];
$sql = "select * from image where id = '$id'";
require_once('dbConnect.php');
$r = mysqli_query($con,$sql);
$result = mysqli_fetch_array($r);
header('content-type: image/jpeg');
echo base64_decode($result['image']);
mysqli_close($con);
}else{
echo "Error";
}
对我在这里做错什么有任何想法吗?
谢谢!
答案 0 :(得分:0)
As we know that, Image parsing we are using Bitmap, or Base64 Ecodder.
I suggest you to use library like Glide, Picasso this is official library...
You don't have to write so much code.
Avoid to use Boiler Plate Code in Development.
Picasso
Picasso.get()
.load(url)
.resize(50, 50)
.centerCrop()
.into(imageView)
Glide
GlideApp.with(context)
.load("http://via.placeholder.com/300.png")
.override(300, 200)
.into(ivImg);