压缩图片处理

1.写这之前最好会      Retrofit获取网络数据   和   Rxjava上游传下游




2.导包和添加网络权限
compile 'com.squareup.retrofit2:retrofit:2.1.0'
    compile 'com.squareup.okhttp3:logging-interceptor:3.3.0'
    compile 'com.squareup.retrofit2:converter-gson:2.1.0'
    compile 'io.reactivex.rxjava2:rxjava:2.1.3'
    compile 'io.reactivex.rxjava2:rxandroid:2.0.1'

<uses-permission android:name="android.permission.INTERNET"></uses-permission>




3.创建接口类什么的我就不详说了


public interface jiekou {

    @GET
    Call<ResponseBody> getBitmap(@Url String url);
}







4.主布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="comqq.example.hasee.myapplication.MainActivity"
    android:orientation="vertical">
    <ImageView
        android:id="@+id/iv"
        android:layout_width="400dp"
        android:layout_height="400dp" />
        <TextView
            android:id="@+id/tv1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />


        <TextView
            android:id="@+id/tv2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

  <TextView
            android:id="@+id/tv3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
            android:text="质量压缩,保存到本地"
            android:id="@+id/but1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="cc"
            />
        <Button
            android:text="采样率压缩"
            android:id="@+id/but2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="cc"
            />
        <Button
            android:text="尺寸压缩"
            android:id="@+id/but3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="cc"
            />
        <Button
            android:text="缩放图片2"
            android:id="@+id/but4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="cc"
            />

    </LinearLayout>


</LinearLayout>






5.主函数
package comqq.example.hasee.myapplication;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.function.Consumer;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;

public class MainActivity extends AppCompatActivity {
private ImageView iv;
private TextView tv1,tv2,tv3;
private String baseUrl = "http://pic.xiami.net";
private String url = "http://pic9.nipic.com/20100823/4361515_000842599423_2.jpg";
private int contentLength;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        iv=findViewById(R.id.iv);
        tv1=findViewById(R.id.tv1);
        tv2=findViewById(R.id.tv2);
        tv3=findViewById(R.id.tv3);

    }
    public void cc(View view) throws IOException {
        switch (view.getId()) {
            case R.id.but1:
                Observable.create(new ObservableOnSubscribe<String>() {
                    @Override
                    public void subscribe(ObservableEmitter<String> e) throws Exception {
                        ResponseBody body = new Retrofit.Builder()
                                .baseUrl(baseUrl)//资源地址
                                .build()
                                .create(jiekou.class)//接口
                                .getBitmap(url)//这是图片地址
                                .execute()//同步请求
                                .body();
                        contentLength = (int) body.contentLength() / 1024;
                        InputStream stream = body.byteStream();
                        //得到图片的Bitmap
                        Bitmap bitmap = BitmapFactory.decodeStream(stream);

                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        //质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                        int options = 100;
                        while (baos.toByteArray().length / 1024 > 100) {  //循环判断如果压缩后图片是否大于100kb,大于继续压缩
                            //重置baos即清空baos
                            baos.reset();
                            //这里压缩options%,把压缩后的数据存放到baos中
                            bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);
                            options -= 10;//每次都减少10
                        }
                        //这是要存放图片的地址
                        File file = new File(Environment.getExternalStorageDirectory(), "load3.jpg");
                        FileOutputStream out = new FileOutputStream(file);
                        //开始往地址里面图片
                        out.write(baos.toByteArray());
                        out.close();
                        baos.close();
                        e.onNext(file.getPath());
                    }
                })
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new io.reactivex.functions.Consumer<String>() {
                            @Override
                            public void accept(String s) throws Exception {
                                tv1.setText("原始大小:" + contentLength + "kb");
                                File file = new File(s);
                                int fileLenth = (int) (file.length() / 1024);
                                tv2.setText("保存后大小:" + fileLenth + "kb");
                                Bitmap bitmap = BitmapFactory.decodeFile(s);

                                int byteCount = bitmap.getByteCount() / 1024;
                                tv3.setText("加载到内存的大小:" + byteCount);
                                iv.setImageBitmap(bitmap);
                            }
                        });

                break;
            case R.id.but2:
                Observable.create(new ObservableOnSubscribe<String>() {
                    @Override
                    public void subscribe(ObservableEmitter<String> e) throws Exception {
                        ResponseBody body = new Retrofit.Builder()
                                .baseUrl(baseUrl)
                                .build()
                                .create(jiekou.class)
                                .getBitmap(url)
                                .execute()
                                .body();
                        contentLength = (int) body.contentLength() / 1024;
                        InputStream stream = body
                                .byteStream();
                        File file = new File(Environment.getExternalStorageDirectory(), "load4.jpg");
                        FileOutputStream out = new FileOutputStream(file);
                        out.write(body.bytes());
                        out.close();
                        String filePath = file.getPath();
                        e.onNext(filePath);
                    }
                })
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new io.reactivex.functions.Consumer<String>() {
                            @Override
                            public void accept(String path) throws Exception {
                                tv1.setText("原始大小:" + contentLength + "kb");
                                File file = new File(path);
                                int fileLenth = (int) (file.length() / 1024);
                                tv2.setText("保存后大小:" + fileLenth + "kb");

                                //使用采样率进行压缩
                                BitmapFactory.Options newOpts = new BitmapFactory.Options();
                                //开始读入图片,此时把options.inJustDecodeBounds 设回true了
                                newOpts.inJustDecodeBounds = true;
                                //此时返回bitmap为空
                                Bitmap bitmap = BitmapFactory.decodeFile(path, newOpts);

                                newOpts.inJustDecodeBounds = false;
                                int w = newOpts.outWidth;
                                int h = newOpts.outHeight;
                                //现在主流手机比较多是1280*720分辨率,所以高和宽我们设置为
                                //这里设置高度为1280f
                                float hh = 1280f;
                                //这里设置宽度为720f
                                float ww = 720f;
                                //缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
                                //be=1表示不缩放
                                int be = 1;
                                if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
                                    be = (int) (newOpts.outWidth / ww);
                                } else if (w < h && h > hh) {//如果高度高的话根据高度固定大小缩放
                                    be = (int) (newOpts.outHeight / hh);
                                }
                                if (be <= 0) {
                                    be = 1;
                                }

                                //设置缩放比例
                                newOpts.inSampleSize = be;
                                //重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了
                                bitmap = BitmapFactory.decodeFile(path, newOpts);

                                //压缩好比例大小后再进行质量压缩
                                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
                                int options = 100;
                                while (baos.toByteArray().length / 1024 > 100) {  //循环判断如果压缩后图片是否大于100kb,大于继续压缩
                                    //重置baos即清空baos
                                    baos.reset();
                                    //这里压缩options%,把压缩后的数据存放到baos中
                                    bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);
                                    options -= 10;//每次都减少10
                                }

                                int len = baos.toByteArray().length / 1024;
                                tv3.setText("内存中的大小:" + len + "kb");
                                //把压缩后的数据baos存放到ByteArrayInputStream中
                                ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
                                //把ByteArrayInputStream数据生成图片
                                Bitmap bitmap3 = BitmapFactory.decodeStream(isBm, null, null);
                                tv3.setText("保存后大小:" + fileLenth + "kb"+"bitmap:"+bitmap3.getByteCount()/1024+"--");
                                iv.setImageBitmap(bitmap3);
                            }
                        });

                break;
            case R.id.but3:
                Observable.create(new ObservableOnSubscribe<String>() {
                    @Override
                    public void subscribe(ObservableEmitter<String> e) throws Exception {
                        ResponseBody body = new Retrofit.Builder()
                                .baseUrl(baseUrl)
                                .build()
                                .create(jiekou.class)
                                .getBitmap(url)
                                .execute()
                                .body();
                        contentLength = (int) body.contentLength() / 1024;
                        InputStream stream = body
                                .byteStream();
                        Bitmap bmp = BitmapFactory.decodeStream(stream);

                        // 尺寸压缩倍数,值越大,图片尺寸越小
                        int ratio = 2;
                        // 压缩Bitmap到对应尺寸
                        //int width,宽 int height,高 Config config,决定图片质量.
                        Bitmap result = Bitmap.createBitmap(bmp.getWidth() / ratio, bmp.getHeight() / ratio, Bitmap.Config.ARGB_8888);
                        Canvas canvas = new Canvas(result);
                        Rect rect = new Rect(0, 0, bmp.getWidth() / ratio, bmp.getHeight() / ratio);
                        canvas.drawBitmap(bmp, null, rect, null);

                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        // 把压缩后的数据存放到baos中
                        result.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                        File file = new File(Environment.getExternalStorageDirectory(), "load5.jpg");
                        FileOutputStream fos = new FileOutputStream(file);
                        fos.write(baos.toByteArray());
                        fos.flush();
                        fos.close();
                        String filePath = file.getPath();
                        e.onNext(filePath);
                    }
                })
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new io.reactivex.functions.Consumer<String>() {
                            @Override
                            public void accept(String path) throws Exception {
                                tv1.setText("原始大小:" + contentLength + "kb");
                                File file = new File(path);
                                int fileLenth = (int) (file.length() / 1024);
                                tv2.setText("保存后大小:" + fileLenth + "kb");

                                Bitmap bitmap = BitmapFactory.decodeFile(path);
                                int byteCount = bitmap.getByteCount() / 1024;
                                tv3.setText("加载到内存的大小:" + byteCount);
                                iv.setImageBitmap(bitmap);
                            }
                        });
                break;
            case R.id.but4:
                Observable.create(new ObservableOnSubscribe<String>() {
                    @Override
                    public void subscribe(ObservableEmitter<String> e) throws Exception {
                        ResponseBody body = new Retrofit.Builder()
                                .baseUrl(baseUrl)
                                .build()
                                .create(jiekou.class)
                                .getBitmap(url)
                                .execute()
                                .body();
                        contentLength = (int) body.contentLength() / 1024;
                        InputStream stream = body
                                .byteStream();
                        Bitmap image = BitmapFactory.decodeStream(stream);

                        ByteArrayOutputStream out = new ByteArrayOutputStream();
                        image.compress(Bitmap.CompressFormat.JPEG, 85, out);
                        int size = contentLength;
                        //--原大小/内存小小后,开平方根.
                        float zoom = (float)Math.sqrt(size * 1024 / (float)out.toByteArray().length);
//
                        Matrix matrix = new Matrix();
                        matrix.setScale(zoom, zoom);

                        Bitmap result = Bitmap.createBitmap(image, 0, 0, image.getWidth(), image.getHeight(), matrix, true);
                        //清空.
                        out.reset();
                        result.compress(Bitmap.CompressFormat.JPEG, 85, out);
                        while(out.toByteArray().length > size * 1024){
                            Toast.makeText(MainActivity.this,out.toByteArray().length+"***", Toast.LENGTH_SHORT).show();
                            matrix.setScale(0.9f, 0.9f);
                            result = Bitmap.createBitmap(result, 0, 0, result.getWidth(), result.getHeight(), matrix, true);
                            out.reset();
                            result.compress(Bitmap.CompressFormat.JPEG, 85, out);
                        }

                        File file = new File(Environment.getExternalStorageDirectory(), "load6.jpg");
                        FileOutputStream fos = new FileOutputStream(file);
                        fos.write(out.toByteArray());
                        fos.flush();
                        fos.close();
                        String filePath = file.getPath();
                        e.onNext(filePath);
                    }
                })
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new io.reactivex.functions.Consumer<String>() {
                            @Override
                            public void accept(String path) throws Exception {
                                tv1.setText("原始大小:" + contentLength + "kb");
                                File file = new File(path);
                                int fileLenth = (int) (file.length() / 1024);
                                tv2.setText("保存后大小:" + fileLenth + "kb");

                                Bitmap bitmap = BitmapFactory.decodeFile(path);
                                int byteCount = bitmap.getByteCount() / 1024;
                                tv3.setText("加载到内存的大小:" + byteCount);
                                iv.setImageBitmap(bitmap);
                            }
                        });

                break;

        }

    }

}










  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值