gpt4 book ai didi

Android - 如何加载大图像(将其转换为较小的尺寸)并将其作为 Base64 字节数组发送(避免 OutOfMemory 错误)

转载 作者:行者123 更新时间:2023-11-29 00:17:54 24 4
gpt4 key购买 nike

我想在我的应用程序中将照片图像发送到服务器。 API 使用 Base64 格式的图像。我有图像/照片的路径,现在我想将此路径转换为 ​​Base64 数组。

为了加载图像,我从 here 获得了这段代码(它还将图像调整为最大尺寸) :

private Bitmap getBitmap(String path) {

Uri uri = getImageUri(path);
InputStream in = null;
try {
final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
in = mContentResolver.openInputStream(uri);

// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(in, null, o);
in.close();



int scale = 1;
while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) >
IMAGE_MAX_SIZE) {
scale++;
}
Log.d(TAG, "scale = " + scale + ", orig-width: " + o.outWidth + ",
orig-height: " + o.outHeight);

Bitmap b = null;
in = mContentResolver.openInputStream(uri);
if (scale > 1) {
scale--;
// scale to max possible inSampleSize that still yields an image
// larger than target
o = new BitmapFactory.Options();
o.inSampleSize = scale;
b = BitmapFactory.decodeStream(in, null, o);

// resize to desired dimensions
int height = b.getHeight();
int width = b.getWidth();
Log.d(TAG, "1th scale operation dimenions - width: " + width + ",
height: " + height);

double y = Math.sqrt(IMAGE_MAX_SIZE
/ (((double) width) / height));
double x = (y / height) * width;

Bitmap scaledBitmap = Bitmap.createScaledBitmap(b, (int) x,
(int) y, true);
b.recycle();
b = scaledBitmap;

System.gc();
} else {
b = BitmapFactory.decodeStream(in);
}
in.close();

Log.d(TAG, "bitmap size - width: " +b.getWidth() + ", height: " +
b.getHeight());
return b;
} catch (IOException e) {
Log.e(TAG, e.getMessage(),e);
return null;
}

这是发送图片的代码:

        image = getBitmap(pathToImage);

ByteArrayOutputStream stream = new ByteArrayOutputStream();

String filenameArray[] = fileName.split("\\.");
String extension = filenameArray[filenameArray.length - 1];

if (extension.equalsIgnoreCase("jpg")
|| extension.equalsIgnoreCase("jpeg"))
image.compress(Bitmap.CompressFormat.JPEG, 100, stream);
else
image.compress(Bitmap.CompressFormat.PNG, 100, stream);

image.recycle();
image = null;

byte[] byteArray = stream.toByteArray();

try {
stream.close();
} catch (IOException e1) {

}

stream = null;

ByteArrayOutputStream baos = new ByteArrayOutputStream(
(int) (byteArray.length * 1.5));

JsonGenerator jgenerator = null;

try {
jgenerator = new JsonFactory().createGenerator(baos);

jgenerator.writeStartObject();
jgenerator.writeStringField("fileName", fileName);
// Jackson takes care of the base64 encoding for us
jgenerator.writeBinaryField("content", byteArray);
jgenerator.writeEndObject();
jgenerator.close();

} catch (JsonGenerationException e) {
} catch (IOException e) {
}

HttpClient httpClient = new DefaultHttpClient();

HttpPost httppost = new HttpPost(Globals.URL + "/storageUploadFile");

httppost.setHeader("Token", Globals.Token);
httppost.setHeader("Content-type",
"application/json; charset=utf-8");

httppost.setEntity(new ByteArrayEntity(baos.toByteArray()));

HttpResponse response;
try {
response = httpClient.execute(httppost);

HttpEntity httpentity = response.getEntity();

msg = EntityUtils.toString(httpentity);

jgenerator = null;
httppost = null;
httpClient = null;
httpentity = null;

} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}

有时我在 Bitmap scaledBitmap = Bitmap.createScaledBitmap(b, (int) x, (int) y, true); 行或 jgenerator.writeBinaryField( "内容", byteArray);

你能帮我修改代码以避免OutOfMemory错误吗?关于如何将图像从文件转换为 Base64 并将其作为 HTTPPost 发送,您有一些技巧吗?

最佳答案

你试过Picasso了吗?图书馆?

AsyncTask<String,Void,Void> downloadAndResizePictureTask = new AsyncTask<String,Void,Void>(){
@Override
public Void doInBackground(String... params){
//assuming params[0] is a valid url
Bitmap bmp = Picasso.with(getActivity()).load(params[0]).resize(150,150).get();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
//do what needs to be done to convert to Base64

}
}

关于Android - 如何加载大图像(将其转换为较小的尺寸)并将其作为 Base64 字节数组发送(避免 OutOfMemory 错误),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25265944/

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