安卓:自定义照片尺寸
我有在移动拍摄照片,然后上传到服务器一个应用程序。我想首先检查照片的尺寸,然后根据实际的照片尺寸将照片尺寸缩小到某个特定的尺寸。实际上在服务器上它不允许具有比特定大小(比如200kb)更大的照片。安卓:自定义照片尺寸
或者,我可以限制相机拍摄的照片只在特定大小甚至有的一个改变相机的设置。
很多问题在这里问其检索照片的宽度和高度。但我想以字节自定义大小。
要我的使用cameraIntent
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
这是唯一可能的解决方案据我所知,以减少大小..
public void onActivityResult(int requestcode, int resultcode, Intent data) {
if (resultcode == RESULT_OK) {
if (requestcode == SELECT_PICTURE) {
Uri uri = data.getData();
String imagePath = getPath(uri);
int SCALE = 2;
try{
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = SCALE;
Bitmap bitmap= BitmapFactory.decodeFile(imagePath, o2);
OutputStream os = new FileOutputStream(imagePath);
bitmap.compress(Bitmap.CompressFormat.PNG, 85, os);
os.flush();
os.close();
File file = new File(imagePath);
Log.i("Bitmap", "Height Width "+bitmap.getHeight()+" "+bitmap.getWidth());
Log.i("File","Size in bytes "+file.length());
while(file.length()>100*1024)
{
SCALE +=2;
o2.inSampleSize = SCALE;
bitmap= BitmapFactory.decodeFile(imagePath, o2);
os = new FileOutputStream(imagePath);
bitmap.compress(Bitmap.CompressFormat.PNG, 85, os);
os.flush();
os.close();
file = new File(imagePath);
Log.i("Bitmap", "Height Width "+bitmap.getHeight()+" "+bitmap.getWidth());
Log.i("File","Size in bytes "+file.length());
}
bitmap = BitmapFactory.decodeFile(imagePath, o2);
}
catch (Exception e) {
e.printStackTrace();
}
txtimagepath.setText(imagePath);
}
}
}
protected String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int columnIndex = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(columnIndex);
}
当您更改宽度和高度
这是什么imagePath? –
当然,这是一个字符串。我已经更新了答案,[仅供参考,因为您已经从相机/画廊获得了位图,我认为您知道它。第二,但更重要的是“?”会做..不需要4.] – MKJParekh
什么是这个getPath(uri)方法,这个方法中的代码是什么? –
不能动态指定生成的文件的大小和做缩放打开摄像头。您必须重新调整高度和宽度的大小,这反过来会减小文件大小。
可能,重复的方法,以为终于可以让您的限度内的文件大小会有所帮助。我想不出任何其他解决方案。至少,Android SDK不提供这样的API。
如果您想保留宽/高,那么你可以尝试压缩技术,这将导致质量损失,并最终文件大小。但是,再次,没有直接的API来实现这一目标。
Bitmap bt=Bitmap.createScaledBitmap(YourOrignalBitmap,320, 300, false);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bt.compress(Bitmap.CompressFormat.PNG,100, bos);
在这里你可以修复的大小和保持图像质量..
的照片,那么显然字节的大小也会改变。你试过了吗? –
确定我会尝试,但我想保持照片的高度和宽度... –
我不认为这是可能的高度和宽度不变,改变大小。虽然可能,但图像的质量也将分别降低。 –