Android接收服務返回的圖片流

服務器返回圖片流

public static void getImageBitmapFromServer(final ImageView img, final Context context, String s) {
       okhttpxxx.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    byte[] data = getBytesFromInputStream(response.body().byteStream());
                   //Bitmap.CompressFormat.PNG, 100, baos
                    YuvImage yuvimage=new YuvImage(data, ImageFormat.YUY2, 40,20, null); //20、20分別是圖的寬度與高度
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    yuvimage.compressToJpeg(new Rect(0, 0,20, 20), 100, baos);//80--JPG圖片的質量[0-100],100最高
                    byte[] jdata = baos.toByteArray();
                    Bitmap bitmap = BitmapFactory.decodeByteArray(jdata, 0, jdata.length);
                    Log.i("test", "onResponse: bitmap:"+bitmap);
                    img.setImageBitmap(bitmap);
                   // Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length);
                    //Log.i("test", "onResponse: bm:"+bm);
                } catch (Exception e) {
                    e.printStackTrace();
                  
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                
            }
        });

    }
    public static byte[] getBytesFromInputStream(InputStream is) throws IOException {
        ByteArrayOutputStream outstream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024]; // 用數據裝
        int len = -1;
        while ((len = is.read(buffer)) != -1) {
            outstream.write(buffer, 0, len);
        }
        outstream.close();   // 關閉流一定要記得。

        return outstream.toByteArray();
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章