我正在从图库中获取图像,并试图降低其质量,然后再将其上传到服务器上,但是我没有正确的方法。
下面是我的代码:
openGallery.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent();
i.setType("image/*");
i.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(i,"Select picture"),GALLERY_IMAGE);
}
});
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GALLERY_IMAGE && resultCode == RESULT_OK && data != null){
selectedImage = data.getData();
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),selectedImage);
} catch (IOException e) {
e.printStackTrace();
}
if(bitmap != null){
bookImage.setImageBitmap(bitmap);
}
}
else{
TastyToast.makeText(getApplicationContext(),"No image selected",TastyToast.LENGTH_SHORT,TastyToast.INFO).show();
}
}
请让我知道我应该在上面的代码中添加些什么才能获得结果,我们将不胜感激。
谢谢
答案 0 :(得分:0)
我使用以下代码缩小和设置JPG质量。下面的代码将JPG流保存到文件中,但是您应该能够发送到内存流和字节数组。
话虽如此,您还应该考虑让ANDROID向您返回缩小的图片。特别是对于较旧的设备,您的应用程序可能没有足够的内存来存储完整尺寸的图片。抱歉,我没有任何代码可让您执行此操作。
// Shrink to fit picture in a max size
Point newSize = util.fitSizeInBounds(new Point(rawBitmap.getWidth(), rawBitmap.getHeight()), new Point(_maxPicSize, _maxPicSize));
if (rawBitmap.getWidth() > newSize.x || rawBitmap.getHeight() > newSize.y) {
scaledBitmap = Bitmap.createScaledBitmap(rawBitmap, newSize.x, newSize.y, false);
// Because I was concerned about memory leaks, I call recycle, but maybe this is not nessessary
rawBitmap.recycle(); rawBitmap = null;
}
else {
scaledBitmap = rawBitmap; rawBitmap = null;
}
// Save file
try {
FileOutputStream outStream = new FileOutputStream(_tempDir + fileName);
if (ext.equals("png")) scaledBitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
else scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 70, outStream); // Here you can compress JPG (70% quality here)
outStream.close();
}
catch (Exception e) {}
public Point fitSizeInBounds(Point size, Point bounds) {
// return size that can fit in bounds. Result will keep same proportion as orig size
int newWidth = size.x;
int newHeight = size.y;
if (newWidth > bounds.x) {
newHeight = (newHeight * bounds.x) / newWidth;
newWidth = bounds.x;
}
if (newHeight > bounds.y) {
newWidth = (newWidth * bounds.y) / newHeight;
newHeight = bounds.y;
}
return new Point(newWidth, newHeight);
}