gpt4 book ai didi

android - 在android中上传高分辨率图像

转载 作者:太空狗 更新时间:2023-10-29 14:18:57 24 4
gpt4 key购买 nike

您好,我想将高分辨率图像上传到我的 PHP 服务器。现在我正在使用编码字符串将图像发送到我的服务器。这里的问题是我无法上传高分辨率图像,这导致我内存不足。我的图片大约有 1-2 Mb 大。这是我如何将图像上传到服务器的 fragment 。

String encodedPagerpath="";
if(!FILE_PAGER_PATH.equals("") && FILE_PAGER_PATH.length()!=0)
{
byte [] b=imageTobyteArray(FILE_PAGER_PATH,150,150);
if(b!=null)
{
encodedPagerpath=Base64.encodeToString(b, Base64.DEFAULT);
if(encodedPagerpath==null || encodedPagerpath.equals("")){
encodedPagerpath="";
}
}
}

//Convert image into byte array
static byte[] imageTobyteArray(String path,int width,int height)
{ byte[] b = null ;
if(!path.equals("") || path.length()!=0)
{


// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
options.inDither=true;//optional
options.inPreferredConfig=Bitmap.Config.RGB_565;//optional

Bitmap bm = BitmapFactory.decodeFile(path,options);

options.inSampleSize = calculateInSampleSize(options, width, height);

// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;

bm=BitmapFactory.decodeFile(path,options);


ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 70, baos); //bm is the bitmap object
b= baos.toByteArray();
}
return b;
}

public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;

if (height > reqHeight || width > reqWidth) {

// Calculate ratios of height and width to requested height and width
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);

// Choose the smallest ratio as inSampleSize value, this will guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}

return inSampleSize;
}

我在 json 对象中发送这个编码字符串。我可以采用更好的方法吗?如果我超过 150X150,它会导致 OOM。我想在不降低质量的情况下上传高分辨率图像文件。

最佳答案

我在上传图片文件的 POST 请求中使用了 Apache Commons 库 (httpmime.jar) 中的 MultipartEntity:

public static HttpEntity createMultipartBody(File file) throws IOException{
MultipartEntity entity = new MultipartEntity();
entity.addPart(key, new FileBody(file));
return entity;
}

然后创建简单的 HttpPost,为它设置 Entity 并将它发送到服务器:

HttpPost httpPostRequest = new HttpPost(SOME_URL);
httpPostRequest.setEntity(createMultipartBody(SOME_FILE_TO_UPLOAD));

HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(httpPostRequest);

关于android - 在android中上传高分辨率图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18712197/

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