如何在上传到服务器时减小图像大小

时间:2016-09-02 07:52:57

标签: android image-uploading

我有一个从服务器上传和下载图片的应用,这是我从图库到服务器上传图片的代码。我想在上传图片之前缩小图片大小。怎么做?

private void uploadmap(final String sfile){

int fbyte,buffersize,cbuffer;

int maxbuffer=1024*1024;

File f=new File(sfile); 

try{

    FileInputStream fis=new FileInputStream(f);

    ///////////////////////////
    URL url=new URL(Main.url+"uploadmap.php");
    ///////////////////////////////////////////////

    HttpURLConnection con=(HttpURLConnection) url.openConnection();

    con.setDoInput(true);
    con.setDoOutput(true);
    con.setRequestMethod("POST");
    con.setUseCaches(false);

    con.setRequestProperty("Connection", "keep-Alive");
    con.setRequestProperty("ENCType", "multipart/form-data");
    con.setRequestProperty("Content-Type", "multipart/form-data; boundary=*****");
    con.setRequestProperty("uploaded-file", sfile);


    DataOutputStream dos =new DataOutputStream(con.getOutputStream());

    dos.writeBytes("--*****\r\nContent-Disposition: form-data; name=\"uploaded_file\"; filename=\""+sfile+"\"\r\n\r\n");

    fbyte=fis.available();
    buffersize=Math.min(fbyte, maxbuffer);
    byte[] buffer=new byte[buffersize];

    cbuffer=fis.read(buffer,0,buffersize);

    while(cbuffer>0){
        dos.write(buffer,0,buffersize);
        fbyte=fis.available();
        buffersize=Math.min(fbyte, maxbuffer);
        cbuffer=fis.read(buffer,0,buffersize);

    }

    dos.writeBytes("\r\n--*****--\r\n");

    if(con.getResponseCode()==200){

        runOnUiThread(new Runnable(){

            @Override
            public void run() {

                maptv.setText(getname(sfile));
                dialog.dismiss();
                sendmap.setVisibility(View.GONE);
                Toast.makeText(getApplicationContext(), "uploaded", Toast.LENGTH_LONG).show();      

            }
        });

        fis.close();
        dos.flush();
        dos.close();

    }

}catch(final Exception e){

    runOnUiThread(new Runnable(){

        @Override
        public void run() {

            pr.dismiss();

            Toast.makeText(getApplicationContext(), "not upload", Toast.LENGTH_LONG).show();
        }
    });
}

我希望使用此代码进行上传来缩小图像尺寸,我不想降低图像质量。

4 个答案:

答案 0 :(得分:1)

//Image attaching
MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
File file;
multipartEntity.addBinaryBody("someName", file,     ContentType.create("image/jpeg"), file.getName());
//Json string attaching
String json;
multipartEntity.addPart("someName", new StringBody(json, ContentType.TEXT_PLAIN));

答案 1 :(得分:0)

在将图像转换为文件之前尝试压缩图像位图或者您可以使用裁剪图像稍微减小尺寸..如果您不想压缩,可以通过将文件更改为zip来发送数据这里是完整的教程要做它 link

答案 2 :(得分:0)

我的新代码可以减少图像尺寸(不会丢失质量)并将其发送到服务器

它是一个从图库中选择图像的按钮:

    upmap.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View arg0) {

        Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.btnanim);
        upmap.startAnimation(animation);
        map.setImageResource(0);
        Intent i=new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(i, 1);




    }
});

它是一个上传图像到服务器的按钮:

             sendmap.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {

                    Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.btnanim);
                    sendimg.startAnimation(animation);


                    dialog = new ProgressDialog(sendlocation.this);
                    dialog.setTitle("uploading...");
                    dialog.setMessage("please wait");
                    dialog.show();

                    new Thread(new Runnable(){
                        @Override
                        public void run() {
                            uploadmap(compressImage(mappath));
                        }
                    }).start();



                }
            }); 

它是我选择图像的方法:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);

if(requestCode==1 && resultCode==RESULT_OK && data!=null){

    Uri img =data.getData();

    String[] af={MediaStore.Images.Media.DATA};

    Cursor cu=getContentResolver().query(img, af, null, null, null);

    cu.moveToFirst();

    int ci=cu.getColumnIndex(af[0]);



     mappath=cu.getString(ci);



        mappath=cu.getString(ci);

        Bitmap bmImg = BitmapFactory.decodeFile(compressImage(mappath));
        map.setImageBitmap(bmImg);
        upmap.setImageResource(R.drawable.changeimage);


            sendmap.setVisibility(View.VISIBLE);



}

我上传图片的方法:

private void uploadmap(final String sfile){

int fbyte,buffersize,cbuffer;

int maxbuffer=1024*1024;

File f=new File(sfile);






try{

    FileInputStream fis=new FileInputStream(f);

    ///////////////////////////
    URL url=new URL(Main.url+"uploadmap.php");
    ///////////////////////////////////////////////

    HttpURLConnection con=(HttpURLConnection) url.openConnection();

    con.setDoInput(true);
    con.setDoOutput(true);
    con.setRequestMethod("POST");
    con.setUseCaches(false);

    con.setRequestProperty("Connection", "keep-Alive");
    con.setRequestProperty("ENCType", "multipart/form-data");
    con.setRequestProperty("Content-Type", "multipart/form-data; boundary=*****");
    con.setRequestProperty("uploaded-file", sfile);


    DataOutputStream dos =new DataOutputStream(con.getOutputStream());

    dos.writeBytes("--*****\r\nContent-Disposition: form-data; name=\"uploaded_file\"; filename=\""+sfile+"\"\r\n\r\n");

    fbyte=fis.available();
    buffersize=Math.min(fbyte, maxbuffer);
    byte[] buffer=new byte[buffersize];


    cbuffer=fis.read(buffer,0,buffersize);

    while(cbuffer>0){
        dos.write(buffer,0,buffersize);
        fbyte=fis.available();
        buffersize=Math.min(fbyte, maxbuffer);
        cbuffer=fis.read(buffer,0,buffersize);

    }

    dos.writeBytes("\r\n--*****--\r\n");



    if(con.getResponseCode()==200){

        runOnUiThread(new Runnable(){

            @Override
            public void run() {

                maptv.setText(getname(uriSting));
                dialog.dismiss();
                sendmap.setVisibility(View.GONE);
                Toast.makeText(getApplicationContext(), "uploaded", Toast.LENGTH_LONG).show();

                uriSting="";


            }
        });

        fis.close();
        dos.flush();
        dos.close();

    }



}catch(final Exception e){

    runOnUiThread(new Runnable(){

        @Override
        public void run() {

            pr.dismiss();

            Toast.makeText(getApplicationContext(), 
              "Upload failed", Toast.LENGTH_LONG).show();
            }
         });
      }

    }

及其减少图像尺寸的方法:

public String compressImage(String imageUri) {

    String filePath = getRealPathFromURI(imageUri);
    Bitmap scaledBitmap = null;

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    Bitmap bmp = BitmapFactory.decodeFile(filePath, options);

    int actualHeight = options.outHeight;
    int actualWidth = options.outWidth;

    float maxHeight = 816.0f;
    float maxWidth = 612.0f;
    float imgRatio = actualWidth / actualHeight;
    float maxRatio = maxWidth / maxHeight;

    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;

        }
    }



    options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight);

    options.inJustDecodeBounds = false;

    options.inPurgeable = true;
    options.inInputShareable = true;
    options.inTempStorage = new byte[16 * 1024];

    try {

        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));


    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);


        scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    return filename;

}

public String getFilename() {
    File file = new File(Environment.getExternalStorageDirectory().getPath(), "MyFolder/Images");
    if (!file.exists()) {
        file.mkdirs();
    }
    String uriSting = (file.getAbsolutePath() + "/" + System.currentTimeMillis() + ".jpg");
    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;
}

答案 3 :(得分:0)

这是一个将图像压缩到所需大小的功能

    public static byte[] getCompressdImage(Bitmap bMap) {



    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] bmpPicByteArray = null;
    int lBitmapSize = MAX_IMAGE_COMPRESSED_SIZE;
    // Log.v("ImageUtils", "Size:" + lBitmapSize);
    int lQuality = 105;
    while (lBitmapSize >= MAX_IMAGE_COMPRESSED_SIZE && lQuality > 10) {
        lQuality -= 10;
        baos = new ByteArrayOutputStream();
        bMap.compress(Bitmap.CompressFormat.JPEG, lQuality, baos);
        bmpPicByteArray = baos.toByteArray();
        lBitmapSize = bmpPicByteArray.length;
    }
    // Log.v("ImageUtils", "Size After compress:" + lBitmapSize);
    return baos.toByteArray();

    }