gpt4 book ai didi

上传前Android图像调整大小(重新采样/下采样)

转载 作者:可可西里 更新时间:2023-11-01 16:34:16 26 4
gpt4 key购买 nike

private void doFileUpload(){

File file1 = new File(selectedPath1);

String urlString = "http://example.com/upload_media_test.php";
try
{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlString);
FileBody bin1 = new FileBody(file1);

MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("uploadedfile1", bin1);
reqEntity.addPart("user", new StringBody("User"));
post.setEntity(reqEntity);

HttpResponse response = client.execute(post);
resEntity = response.getEntity();
final String response_str = EntityUtils.toString(resEntity);

if (resEntity != null) {
Log.i("RESPONSE",response_str);
runOnUiThread(new Runnable(){
public void run() {
try {
res.setTextColor(Color.GREEN);
res.setText("n Response from server : n " + response_str);
Toast.makeText(getApplicationContext(),"Upload Complete. Check the server uploads directory.", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
catch (Exception ex){
Log.e("Debug", "error: " + ex.getMessage(), ex);
}
}

我从互联网上得到这个代码。它可以工作,但是当我尝试上传大于 1MB 的文件时,

我遇到文件大小错误。

我知道如何调整位图图像的大小,但我不知道如何上传调整后的位图图像。

我如何调整大小并使用 filebody 上传?

提前致谢

最佳答案

您不仅需要调整位图的大小,还需要将结果编码为 .jpg 图像。因此,您必须打开文件并将其转换为 Bitmap,将 Bitmap 调整为较小的图像,将图像编码为 byte[] 数组,然后以与上传文件相同的方式上传 byte[] 数组file1.

如果 Bitmap 很大(很明显),您将没有足够的堆内存来打开整个东西,因此您必须使用 BitmapFactory.Options.inSampleSize 打开它。

首先,打开缩小后的位图:

Uri uri = getImageUri(selectedPath1);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4; // Example, there are also ways to calculate an optimal value.
InputStream in = in = contentResolver.openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(in, null, options);

接下来,编码成一个byte[]数组:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
byte[] bitmapdata = bos.toByteArray();

最后,使用 reqEntity.addPart() 直接添加 byte[] 数组,或者写入一个较小的文件并像您当前的示例一样添加该文件。

关于上传前Android图像调整大小(重新采样/下采样),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15534980/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com