转载文章请注明出处:http://write.blog.csdn.net/postedit/13092669
android 通过UrlConnection 或者HttpConnection 访问网络读取图片当下读取量过多或者过大时,就会出现部分的乱码。附下图:
关键处是:public boolean compress (Bitmap.CompressFormat format,
int quality, OutputStream stream)方法。
android api 给的讲解是:
Write
a compressed version of the bitmap to the specified outputstream. If this returns true, the bitmap can be reconstructed by passing a corresponding inputstream to BitmapFactory.decodeStream(). Note: not all Formats support all bitmap configs directly, so it
is possible that the returned bitmap from BitmapFactory could be in a different bitdepth, and/or may have lost per-pixel alpha (e.g. JPEG only supports opaque pixels).
原来的代码:
HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.setDoInput(true); connection.connect(); InputStream fileIn = url.openStream(); OutputStream output=new FileOutputStream(imagefile); byte[] buffer=new byte[1024]; while (fileIn.read(buffer)!=-1) { output.write(buffer); } output.close(); fileIn.close();
其实没有什么思路,就是简单的输入输出。
修改后的代码:
URL url = new URL(reader.getImageUrl(i)); InputStream is = url.openStream(); bitmap = BitmapFactory.decodeStream(is); BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream(imagefile)); bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos); bos.flush(); bos.close(); is.close();
转载文章请注明出处:http://write.blog.csdn.net/postedit/13092669