当前位置: 代码迷 >> 综合 >> Android 图片数据格式转换url图片地址转base64,url转Bitmap,Bitmap转base64,base64转Bitmap,ImageView 加载Bitmap,旋转图片角度
  详细解决方案

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

热度:38   发布时间:2023-12-02 16:54:05.0

Android 常用图片处理  :

1.url图片地址转base64

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

2.url转Bitmap

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

public void urlToBitMap(final String url){new Thread(new Runnable() {@Overridepublic 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.ImageProxy 转 Bitmap

public static Bitmap imageProxyToBitmap(ImageProxy imageProxy) {ByteBuffer byteBuffer = imageProxy.getPlanes()[0].getBuffer();byte[] bytes = new byte[byteBuffer.remaining()];byteBuffer.get(bytes);return BitmapFactory.decodeByteArray(bytes,0,bytes.length);
}

6.ImageView 加载Bitmap图片

imageView.setBackground(new BitmapDrawable(bitmapImg));

上面方法new BitmapDrawable()提示过时,新的方法需要getResources(),用当前上下文context获取,如下:

imageView.setBackground(new BitmapDrawable(Context.getResources(),bitmapImg));

7.旋转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;}

  相关解决方案