我有一个Android应用程序需要从webservice接收几张图片。 但是怎么做呢?
在我的网络服务中,我目前只发送1个图像作为字节[]。
public static byte[] GetMapPicture(string SeqIndex)
{
try
{
byte[] maps;
InterventionEntity interventie = new InterventionEntity(long.Parse(SeqIndex));
MyDocumentsCollection files = interventie.Location.MyDocuments;
maps = null;
foreach (MyDocumentsEntity file in files)
{
if (file.SeqDocumentType == (int)LocationDocumentType.GroundPlanDocument && file.File.Filename.EndsWith(".jpg"))
maps = (file.File.File);
}
return maps;
} catch (Exception e) {
Log.Error(String.Format("Map not send, {0}", e));
return null;
}
}
从我的webservice返回byte []。 但是在我的android项目中,位图没有被解码,因此无效。
public Bitmap getPicture(String message, String url, Context context) throws IOException{
HttpClient hc = MySSLSocketFactory.getNewHttpClient();
Log.d(MobileConnectorApplication.APPLICATION_TAG, "NETWORK - Message to send: "+ message);
HttpPost p = new HttpPost(url);
Bitmap picture;
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setSoTimeout(httpParams, threeMinutes );
p.setParams(httpParams);
try{
if (message != null)
p.setEntity(new StringEntity(message, "UTF8"));
}catch(Exception e){
e.printStackTrace();
}
p.setHeader("Content-type", "application/json");
HttpContext httpcontext = new BasicHttpContext();
httpcontext.setAttribute(ClientContext.COOKIE_STORE, MobileConnectorApplication.COOKIE_STORE);
try{
HttpResponse resp = hc.execute(p,httpcontext);
InputStream is = resp.getEntity().getContent();
picture = BitmapFactory.decodeStream(is); //here is goes wrong
int httpResponsecode = resp.getStatusLine().getStatusCode() ;
checkResponse(url, message, "s", httpResponsecode);
Log.d(MobileConnectorApplication.APPLICATION_TAG, String.format("NETWORK - Response %s", httpResponsecode));
} finally{
}
return picture;
}
有人可以帮我吗?
答案 0 :(得分:1)
假设incomingbytearray是一个字节数组,
Bitmap bitmapimage = BitmapFactory.decodeByteArray(incomingbytearray, 0, incomingbytearray.length);
String filepath = "/sdcard/xyz.png";
File imagefile = new File(filepath);
FileOutputStream fos = new FileOutputStream(imagefile);
bitmapimage.compress(CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
这应该没问题。
编辑:输入到bytearray的流,
InputStream in = new BufferedInputStream(url.openStream(), IO_BUFFER_SIZE);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();
来自Android: BitmapFactory.decodeByteArray gives pixelated bitmap 的转换代码