Java 安卓:点击新建图片,压缩并上传到服务器
完成这项任务的最佳方式是什么? 这两个问题都可以回答- 1) 如何在不丢失清晰度的情况下压缩图像 或 2) 如何在我们的应用程序中以低分辨率启动摄像头 我知道如何通过CameraIntent单击图像,或通过应用程序中的gallery选择图像,并将其上载到服务器。 但是,由于图像可能太大,如果点击高像素密度的相机(我的13MP手机的相机点击3MB图像),但我们不能上传。我需要的大小小于300KB,最好在150KB至200KB左右,而不会失去图片的清晰度。我们有Android中的库吗? 这些图片将是手写文本。 由于这是不可能的,我试着手动将相机的分辨率调低到2MP或VGA,即使这样,照片也足够清晰Java 安卓:点击新建图片,压缩并上传到服务器,java,android,image-processing,picasso,android-camera-intent,Java,Android,Image Processing,Picasso,Android Camera Intent,完成这项任务的最佳方式是什么? 这两个问题都可以回答- 1) 如何在不丢失清晰度的情况下压缩图像 或 2) 如何在我们的应用程序中以低分辨率启动摄像头 我知道如何通过CameraIntent单击图像,或通过应用程序中的gallery选择图像,并将其上载到服务器。 但是,由于图像可能太大,如果点击高像素密度的相机(我的13MP手机的相机点击3MB图像),但我们不能上传。我需要的大小小于300KB,最好在150KB至200KB左右,而不会失去图片的清晰度。我们有Android中的库吗? 这些图片将是
或者,如果我们以低分辨率启动相机,也可以这样做。首先选择您的路径并调用函数
String mImageNewPath=compressImage(imageOldPath);
mImageNewPath是压缩图像的压缩图像或新图像的路径,但不会降低质量
在不降低质量的情况下缩小尺寸的功能
public String compressImage(String imageUri) {
String filePath = getRealPathFromURI(imageUri);
Bitmap scaledBitmap = null;
BitmapFactory.Options options = new BitmapFactory.Options();
// by setting this field as true, the actual bitmap pixels are not loaded in the memory. Just the bounds are loaded. If
// you try the use the bitmap here, you will get null.
options.inJustDecodeBounds = true;
Bitmap bmp = BitmapFactory.decodeFile(filePath, options);
int actualHeight = options.outHeight;
int actualWidth = options.outWidth;
// max Height and width values of the compressed image is taken as 816x612
float maxHeight = 816.0f;
float maxWidth = 612.0f;
float imgRatio = actualWidth / actualHeight;
float maxRatio = maxWidth / maxHeight;
// width and height values are set maintaining the aspect ratio of the image
if (actualHeight > maxHeight || actualWidth > maxWidth) {
if (imgRatio < maxRatio) { imgRatio = maxHeight / actualHeight; actualWidth = (int) (imgRatio * actualWidth); actualHeight = (int) maxHeight; } else if (imgRatio > maxRatio) {
imgRatio = maxWidth / actualWidth;
actualHeight = (int) (imgRatio * actualHeight);
actualWidth = (int) maxWidth;
} else {
actualHeight = (int) maxHeight;
actualWidth = (int) maxWidth;
}
}
// setting inSampleSize value allows to load a scaled down version of the original image
options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight);
// inJustDecodeBounds set to false to load the actual bitmap
options.inJustDecodeBounds = false;
// this options allow android to claim the bitmap memory if it runs low on memory
options.inPurgeable = true;
options.inInputShareable = true;
options.inTempStorage = new byte[16 * 1024];
try {
// load the bitmap from its path
bmp = BitmapFactory.decodeFile(filePath, options);
} catch (OutOfMemoryError exception) {
exception.printStackTrace();
}
try {
scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight,Bitmap.Config.ARGB_8888);
} catch (OutOfMemoryError exception) {
exception.printStackTrace();
}
float ratioX = actualWidth / (float) options.outWidth;
float ratioY = actualHeight / (float) options.outHeight;
float middleX = actualWidth / 2.0f;
float middleY = actualHeight / 2.0f;
Matrix scaleMatrix = new Matrix();
scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);
Canvas canvas = new Canvas(scaledBitmap);
canvas.setMatrix(scaleMatrix);
canvas.drawBitmap(bmp, middleX - bmp.getWidth() / 2, middleY - bmp.getHeight() / 2, new Paint(Paint.FILTER_BITMAP_FLAG));
// check the rotation of the image and display it properly
ExifInterface exif;
try {
exif = new ExifInterface(filePath);
int orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION, 0);
Log.d("EXIF", "Exif: " + orientation);
Matrix matrix = new Matrix();
if (orientation == 6) {
matrix.postRotate(90);
Log.d("EXIF", "Exif: " + orientation);
} else if (orientation == 3) {
matrix.postRotate(180);
Log.d("EXIF", "Exif: " + orientation);
} else if (orientation == 8) {
matrix.postRotate(270);
Log.d("EXIF", "Exif: " + orientation);
}
scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0,
scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix,
true);
} catch (IOException e) {
e.printStackTrace();
}
FileOutputStream out = null;
String filename = getFilename();
try {
out = new FileOutputStream(filename);
// write the compressed bitmap at the destination specified by filename.
scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return filename;
}
public String getFilename() {
File file = new File(Environment.getExternalStorageDirectory().getPath(), "Visitor Management/VisitorPicture");
if (!file.exists()) {
file.mkdirs();
}
String uriSting = (file.getAbsolutePath() + "/" + "IMG_"+System.currentTimeMillis() + ".png");
return uriSting;
}
private String getRealPathFromURI(String contentURI) {
Uri contentUri = Uri.parse(contentURI);
Cursor cursor = getContentResolver().query(contentUri, null, null, null, null);
if (cursor == null) {
return contentUri.getPath();
} else {
cursor.moveToFirst();
int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(index);
}
}
public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int heightRatio = Math.round((float) height/ (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; } final float totalPixels = width * height; final float totalReqPixelsCap = reqWidth * reqHeight * 2; while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
inSampleSize++;
}
return inSampleSize;
}
公共字符串压缩图像(字符串图像URI){
字符串filePath=getRealPathFromURI(imageUri);
位图缩放位图=空;
BitmapFactory.Options=new-BitmapFactory.Options();
//通过将此字段设置为true,实际位图像素不会加载到内存中。只加载边界。如果
//如果您尝试在此处使用位图,将得到null。
options.inJustDecodeBounds=true;
位图bmp=BitmapFactory.decodeFile(文件路径,选项);
int实际高度=options.outHeight;
int actualWidth=options.outWidth;
//压缩图像的最大高度和宽度值为816x612
浮动最大高度=816.0f;
浮动最大宽度=612.0f;
浮动高度=实际宽度/实际高度;
浮点最大比值=最大宽度/最大高度;
//设置宽度和高度值以保持图像的纵横比
如果(实际高度>最大高度| |实际宽度>最大宽度){
if(imgRatiomaxRatio){
imgRatio=最大宽度/实际宽度;
实际高度=(int)(imgRatio*实际高度);
实际宽度=(int)最大宽度;
}否则{
实际高度=(int)最大高度;
实际宽度=(int)最大宽度;
}
}
//设置inSampleSize值允许加载原始图像的缩小版本
options.inSampleSize=calculateInSampleSize(选项、实际宽度、实际高度);
//inJustDecodeBounds设置为false以加载实际位图
options.inJustDecodeBounds=false;
//此选项允许android在内存不足时声明位图内存
options.inpurgable=true;
options.inInputShareable=true;
options.inTempStorage=新字节[16*1024];
试一试{
//从位图路径加载位图
bmp=BitmapFactory.decodeFile(文件路径,选项);
}捕获(OutOfMemoryError异常){
异常。printStackTrace();
}
试一试{
scaledbimat=Bitmap.createBitmap(实际宽度、实际高度、Bitmap.Config.ARGB_8888);
}捕获(OutOfMemoryError异常){
异常。printStackTrace();
}
浮动比率=实际宽度/(浮动)选项。向外宽度;
浮动比率=实际高度/(浮动)选项。超出高度;
浮动中间点x=实际宽度/2.0f;
浮动中间Y=实际高度/2.0f;
矩阵scaleMatrix=新矩阵();
scaleMatrix.setScale(ratioX、ratioY、middleX、middleY);
画布画布=新画布(缩放位图);
canvas.setMatrix(scaleMatrix);
drawBitmap(bmp,middleX-bmp.getWidth()/2,middleY-bmp.getHeight()/2,新绘制(Paint.FILTER_位图_标志));
//检查图像的旋转并正确显示
出口接口;
试一试{
exif=新的ExifInterface(文件路径);
int-orientation=exif.getAttributeInt(
ExiFinInterface.TAG_方向,0);
Log.d(“EXIF”,“EXIF:+方向”);
矩阵=新矩阵();
如果(方向==6){
矩阵旋转后(90);
Log.d(“EXIF”,“EXIF:+方向”);
}否则如果(方向==3){
矩阵旋转后(180);
Log.d(“EXIF”,“EXIF:+方向”);
}否则如果(方向==8){
矩阵旋转后(270);
Log.d(“EXIF”,“EXIF:+方向”);
}
scaledBitmap=Bitmap.createBitmap(scaledBitmap,0,0,
scaledBitmap.getWidth(),scaledBitmap.getHeight(),矩阵,
正确的);
}捕获(IOE异常){
e、 printStackTrace();
}
FileOutputStream out=null;
字符串filename=getFilename();
试一试{
out=新文件输出流(文件名);
//在文件名指定的目标位置写入压缩位图。
scaledBitmap.compress(Bitmap.CompressFormat.JPEG,80,out);
}catch(filenotfounde异常){
e、 printStackTrace();
}
返回文件名;
}
公共字符串getFilename(){
File File=新文件(Environment.getExternalStorageDirectory().getPath(),“访问者管理/VisitorPicture”);
如果(!file.exists()){
mkdirs()文件;
}
字符串uriSting=(file.getAbsolutePath()+“/”+“IMG_”+System.currentTimeMillis()+”.png”);
回归分析;
}
私有字符串getRealPathFromURI(字符串contentURI){
uricontenturi=Uri.parse(contentUri);
Cursor Cursor=getContentResolver().query(contentUri,null,null,null);
if(游标==null){
返回contentUri.getPath();
}否则{
cursor.moveToFirst();
int index=cursor.getColumnIndex(M
public static BufferedImage getScaledImage(Image srcImg, int w, int h) {
BufferedImage resizedImg = new BufferedImage(w, h, Transparency.TRANSLUCENT);
Graphics2D g2 = resizedImg.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(srcImg, 0, 0, w, h, null);
g2.dispose();
return resizedImg;
}
File file = new File(path);
image = ImageIO.read(file);
newImage = getScaledImage(image, int width, int height);
File outputfile = new File("background.png");
ImageIO.write(newImage, "png", outputfile);