Android 图片数据格式转换url图片地址转base64,url转Bitmap,Bitmap转base64,base64转Bitmap,ImageView 加载Bitmap,旋转图片角度

Android 常用图片处理  :

1.url图片地址转base64

     想要将图片地址转成base64格式,需要先将其转为Bitmap,然后再有Bitmap转为base64,使用下面2和3

2.url转Bitmap

     由于是通过地址获取图片,所以在转换的过程中要开启线程去处理,代码如下:

public void urlToBitMap(final String url){
        new Thread(new Runnable() {
            @Override
            public void run() {
                Bitmap bitmap = null;
                URL imageurl = null;

                try {
                    imageurl = new URL(url);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
                try {
                    HttpURLConnection conn = (HttpURLConnection)imageurl.openConnection();
                    conn.setDoInput(true);
                    conn.connect();
                    InputStream is = conn.getInputStream();
                    bitmap = BitmapFactory.decodeStream(is);
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
}

3.Bitmap转base64

public static String bitmapToBase64(Bitmap bitmap){
        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

4.base64转Bitmap

private Bitmap base64ToBitmap(String base64Img){
        byte[] decodedString = Base64.decode(base64Img.split(",")[1], Base64.DEFAULT);
        Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
        return decodedByte;
}

5.ImageView 加载Bitmap图片

imageView.setBackground(new BitmapDrawable(bitmapAll));

6.旋转Bitmap格式图片角度

    /**
     * 旋转图片
     * @param angle  旋转的角度 例如90,例如180
     * @param bitmap 传入的图片bitmap
     * @return Bitmap  返回旋转后的图片bitmap
     */
    public static Bitmap rotaingImageView(int angle, Bitmap bitmap) {
        //旋转图片 动作
        Matrix matrix = new Matrix();

        matrix.postRotate(angle);
        System.out.println("angle2=" + angle);
        // 创建新的图片
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),         bitmap.getHeight(), matrix, true);
        return resizedBitmap;
    }

猜你喜欢

转载自blog.csdn.net/qq_37980878/article/details/110577219