图片相关处理

1 按比例缩放图片

private Bitmap zoomImg(Bitmap bm, int newWidth, int newHeight) {
        // 获得图片的宽高
        int width = bm.getWidth();
        int height = bm.getHeight();
        // 计算缩放比例
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 取得想要缩放的matrix参数
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        // 得到新的图片
        Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
        return newbm;
    }

2 文件生成位图

/**
     * 将文件生成位图
     * @param path
     * @return
     * @throws IOException
     */
    public BitmapDrawable getImageDrawable(String path)
            throws IOException
    {
        //打开文件
        File file = new File(path);
        if(!file.exists())
        {
            return null;
        }

        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] bt = new byte[2048];

        //得到文件的输入流
        InputStream in = new FileInputStream(file);

        //将文件读出到输出流中
        int readLength = in.read(bt);
        while (readLength != -1) {
            outStream.write(bt, 0, readLength);
            readLength = in.read(bt);
        }

        //转换成byte 后 再格式化成位图
        byte[] data = outStream.toByteArray();
        Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);// 生成位图
        BitmapDrawable bd = new BitmapDrawable(bitmap);

        return bd;
    }

3 Bitmap转文件

//方式一
File file=new File(“/storage/emulated/0/1234.jpg”);//将要保存图片的路径 
  try { 
          BufferedOutputStream bos = new BufferedOutputStream(new     FileOutputStream(file)); 
          bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos); 
          bos.flush(); 
          bos.close(); 
    } catch (IOException e) { 
        e.printStackTrace(); 
    } 
}

//方式二
try{
String filePath=”/storage/emulated/0/123.jpg"; 
Bitmap bitmap=BitmapFactory.decodeFile(filePath,getBitmapOption(2)); //将图片的长和宽缩小味原来的1/2
}catch(Exception e){
e.printStackTrace();
}

private Options getBitmapOption(int inSampleSize){ 
System.gc(); 
BitmapFactory.Options options = new BitmapFactory.Options(); 
options.inPurgeable = true; 
options.inSampleSize = inSampleSize; 
return options; 
}

4 图片url转drawable

 /**
     * 图片url转drawable
     * @param url url
     * @param callBack 转换后回调
     */
    public static void getDrawableFromUrl(final String url, final ImageCallBack callBack)
    {
        ThreadUtils.runOnSubThread(new Runnable()
        {
            @Override
            public void run()
            {
                try
                {
                    is = (InputStream) new URL(url).getContent();
                    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
                    int len = -1;
                    byte[] buffer = new byte[1024];
                    while ((len = is.read(buffer)) != -1)
                    {
                        outStream.write(buffer, 0, len);
                    }
                    byte[] imgBuffer = outStream.toByteArray();
                    outStream.close();
                    is.close();
                    is = new ByteArrayInputStream(imgBuffer);
                    Drawable drawable = Drawable.createFromStream(is, "src");
                    callBack.onSuccess(drawable);
                    is.close();
                } catch (IOException e)
                {
                    callBack.onSuccess(null);
                    e.printStackTrace();
                }

            }
        });
    }
    
    
    public interface ImageCallBack
    {
        void onSuccess(Object o);
    }

5 获取bitmap宽高

public static void getBitmapFromUrl(String path,IBitmap iBitmap) {
        ThreadHelper.runOnSubThread(() -> {
            try {
                URL url = new URL(path);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(5000);
                conn.setRequestMethod("GET");
                if (conn.getResponseCode() == 200) {
                    InputStream inputStream = conn.getInputStream();
                    Bitmap bgBitmap = BitmapFactory.decodeStream(inputStream);
                    iBitmap.getWidthAndHeight(bgBitmap.getWidth(),bgBitmap.getHeight());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

public interface IBitmap {
    /*
     * 获取bitmap的宽高
     * @author fflin
     * 2019/3/22  12:02
     */
    void getWidthAndHeight(int width, int height);
}

6 通过流加载本地图片

String path = "/storage/emulated/0/Pictures/Screenshots/Screenshot_2016" +
                    "-07-15-11-13-45.png";
            Bitmap loacalBitmap = getLoacalBitmap(path);

7 加载本地图片

/**
     * 加载本地图片
     *
     * @param url
     * @return
     */
    public Bitmap getLoacalBitmap(String url) {
        try {
            FileInputStream fis = new FileInputStream(url);
            return BitmapFactory.decodeStream(fis);  ///把流转化为Bitmap图片

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            L.e("ChatFrame", "加载本地图片的异常:" + e.getMessage());
            return null;
        }
    }

8 图片压缩

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

9 byte转bitmap

public Bitmap getBitmapFromByte(byte[] temp) {
        if (temp != null) {
            Bitmap bitmap = BitmapFactory.decodeByteArray(temp, 0, temp.length);
            return bitmap;
        } else {
            return null;
        }
    }

10 url转bitmap

/**
    * 从服务器取图片
    * @param url
    * @return
    */
    public static Bitmap getHttpBitmap(String url) {
         URL myFileUrl = null;
         Bitmap bitmap = null;
         try {
              myFileUrl = new URL(url);
         } catch (MalformedURLException e) {
              e.printStackTrace();
         }
         try {
              HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
              conn.setConnectTimeout(0);
              conn.setDoInput(true);
              conn.connect();
              InputStream is = conn.getInputStream();
              bitmap = BitmapFactory.decodeStream(is);
              is.close();
         } catch (IOException e) {
              e.printStackTrace();
         }
         return bitmap;
    }

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值