Android发布高分辨率图像耗尽内存
美好的一天开发者。
我正忙着为Android上传应用程序中的图像。
我也让它工作(代码将在下面)。
但是当我发送大图像(1000万像素)时,我的应用程序因内存exception而崩溃。
对此的解决方案是使用压缩,但如果我想发送全尺寸图像怎么办?
我想也许有一些关于流的东西,但我并不喜欢溪流。 也许urlconnection可能会有所帮助,但我真的不知道。
我给文件名称文件[0到9999] .jpg带有图像日期的post值称为Filedata我为post值dropboxid提供了一个UID
下面的代码有效,但我想解决我的问题,阻止我发送高分辨率图像。
亲切的问候
try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); bitmap.compress(CompressFormat.JPEG, 100, bos); byte[] data = bos.toByteArray(); HttpPost postRequest = new HttpPost(URL_SEND); ByteArrayBody bab = new ByteArrayBody(data, "File" + pad(random.nextInt(9999) + 1) + ".jpg"); MultipartEntity reqEntity = new multipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); reqEntity.addPart("Filedata", bab); reqEntity.addPart("dropboxId", new StringBody(URLEncoder.encode(uid))); postRequest.setEntity(reqEntity); HttpResponse response = httpClient.execute(postRequest); BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); String sResponse; StringBuilder s = new StringBuilder(); while((sResponse = reader.readLine()) != null) { s = s.append(sResponse); } if(d) Log.i(E, "Send response:\n" + s); } catch (Exception e) { if(d) Log.e(E, "Error while sending: " + e.getMessage()); return ERROR; }
使用ByteArrayOutputStream
然后调用#toByteArray()
您实际上将JPEG使用的内存量增加了一倍 。 ByteArrayOutputStream
使用编码的JPEG保留内部数组,当您调用#toByteArray()
它会分配一个新数组并从内部缓冲区复制数据。
考虑将大位图编码为临时文件,并使用FileOutputStream
和FileInputStream
对图像进行编码和发送。
如果没有“上传” – 你的应用程序能够“很好地”存在于我假设的内存中的巨大位图吗?
编辑: FileBody
File img = new File(this is where you put the path of your image) ContentBody cb = new FileBody(img, "File" + pad(random.nextInt(9999) + 1) + ".jpg", "image/jpg", null); MultipartEntity reqEntity = new multipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); reqEntity.addPart("Filedata", cb); reqEntity.addPart("dropboxId", new StringBody(URLEncoder.encode(uid)));