我的android应用程序需要从托管MySQL数据库的php服务器获取一些信息。到目前为止运行良好。服务器将信息编码为JSON并发送,然后我可以很好地解析它。
但现在我还需要获取图像与信息的每一行我从DB得到一起。我得到的信息有一个字段,它指定了对应映像在文件系统中所处的路径。
那么,一旦我得到图像的路径,我如何读取它们,以便我可以将它们与获得的info行一起发送?我可以JSON编码的图像与信息在一起?或者我应该一个接一个地读取它们,一旦我在android应用程序中的信息?如果可以用JSON完成,那么之后如何解析图像的数据?你能举个例子吗?
在textform中获取图像的一种方法是使用base64。我已经在几个web服务中使用了它,实际上有Android的解码器。从API级别8开始,源代码中就有一个。http://developer.android.com/reference/android/util/Base64.html但因为我想瞄准其他水平,我包括它自己。一种简单的方法是将图像保存在数据库中,而不是保存为文件。
这就是我为获取图像和数据所做的。我把它贴出来,如果它能帮助到别人。
这是PHP脚本中在服务器端发送数据的部分:
$i=0;
//$sql contains the result from the query of the data
while($row=mysql_fetch_array($sql)){
$output[]=$row;
//Here we fetch the image from the files table
$query = "SELECT path, type FROM FILES WHERE poi_id = '" . mysql_real_escape_string(trim($output[$i][0])) . "'";
$r = mysql_query($query);
$img = mysql_fetch_array($r);
$bin = base64_encode_image($img[0]);
//Let's append the image and the type to the data output.
$output[$i]['img'] = $bin;
$output[$i]['type'] = $img[1];
$i++;
}
//This method sends the response to the Android app
//You can just use echo(json_encode($output));
RestUtils::sendResponse(200, json_encode($output), 'application/json');
然后在Android应用程序中,解析JSON后,你可以像这样将base64字符串作为图像保存到文件系统中:
public void createImage(String image, String name){
try{
byte[] imageAsBytes = Base64.decode(image.getBytes(), Base64.DEFAULT);
Bitmap img_bitmap = BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length);
FileOutputStream fos = openFileOutput(name, Context.MODE_WORLD_READABLE);
img_bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
}
catch(Exception e){
e.printStackTrace();
}
}
从路径
下载图像 public void DownloadImageFromPath(String path){
InputStream in =null;
Bitmap bmp=null;
ImageView iv = (ImageView)findViewById(R.id.img1);
int responseCode = -1;
try{
URL url = new URL(path);//"http://192.xx.xx.xx/mypath/img1.jpg
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setDoInput(true);
con.connect();
responseCode = con.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK)
{
//download
in = con.getInputStream();
bmp = BitmapFactory.decodeStream(in);
in.close();
iv.setImageBitmap(bmp);
}
}
catch(Exception ex){
Log.e("Exception",ex.toString());
}
}