从多个源创建单个位图会产生损坏的图像

时间:2015-07-02 12:06:50

标签: java android http

我一直在尝试使用来自2个不同HttpURLConnection的http Range标头来模拟从在线源读取图像,但是,生成的图像总是被破坏。如果你看下面的代码,如果我只使用第一个连接的字节来创建位图,我得到正确渲染的图像的一半,但是当我尝试创建新的字节数组,其中包含两个数组来创建位图,我得到损坏的图像,其中图像的一小部分是可见的

那是什么?

HttpURLConnection connection = (HttpURLConnection)new URL(url).openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.connect();
int imageSize = connection.getContentLength();
connection.disconnect();

int threadSize = (int)imageSize/2;                  


byte[] thread1 = new byte[threadSize];
HttpURLConnection connection1 = (HttpURLConnection)new URL(url).openConnection();
connection1.setDoInput(true);
connection1.setDoOutput(true);
String s1 = "bytes=0-"+(threadSize-1);
connection1.setRequestProperty("Range", s1);
connection1.connect();
String contentType1 = connection1.getContentType();
String contentRange1 = connection1.getHeaderField("content-range");
String acceptRange1 = connection1.getHeaderField("Accept-ranges");
int statusCode = connection1.getResponseCode();
int imageSize1 = connection1.getContentLength();
InputStream input1 = connection1.getInputStream();
input1.read(thread1);
input1.close();
connection1.disconnect(); 


downloadIndex += threadSize;

byte[] thread2 = new byte[lastThreadSize];
HttpURLConnection connection2 = (HttpURLConnection)new URL(url).openConnection();
connection2.setDoInput(true);
connection2.setDoOutput(true);
String s2 = "bytes="+threadSize+"-";
connection2.setRequestProperty("Range", s2);
connection2.connect();
String contentType2 = connection2.getContentType();
String contentRange2 = connection2.getHeaderField("content-range");
String acceptRange2 = connection1.getHeaderField("Accept-ranges");
int imageSize2 = connection2.getContentLength();
int statusCode2 = connection2.getResponseCode();
InputStream input2 = connection2.getInputStream();
input2.read(thread2);
input2.close();
connection2.disconnect(); 

int aLen = thread1.length;
int bLen = thread1.length;
byte[] c= new byte[aLen+bLen];
System.arraycopy(a, 0, c, 0, aLen);
System.arraycopy(b, 0, c, aLen, bLen);
ByteArrayInputStream inputStream = new ByteArrayInputStream(x);
image = BitmapFactory.decodeStream(inputStream);//, options);

1 个答案:

答案 0 :(得分:0)

像JPEG和PNG这样的图片流格式并未设置为仅通过附加多个流来创建一个巨型图像。

我会这样做:

  • 下载图像数据并创建位图源1。
  • 下载其他图片数据创建位图源2。
  • 创建一个空的位图dest。设置宽度和高度以同时显示源位图。

    Bitmap dest = new Bitmap(width, height, config);
    
  • 使用目标Canvas构建Bitmap

    Canvas c = new Canvas(dest);
    
  • 将每个源位图绘制到Canvas

     c.drawBitmap(src1, left1, top1, paint);
     c.drawBitmap(src2, left2, top2, paint);
    

然后位图dest将包含两个源图像。