广

android开发

  • IOS开发
  • android开发
  • PHP编程
  • JavaScript
  • ASP.NET
  • ASP编程
  • JSP编程
  • Java编程
  • 易语言
  • Ruby编程
  • Perl编程
  • AJAX
  • 正则表达式
  • C语言
  • 编程开发

    Android处理图像数据转换的各种方法

    2018-04-16 10:56:23 次阅读 稿源:互联网
    广告

    Android中处理图像是一件很常见的事情,这里记录备忘一些亲身使用过的处理图片数据的方法。

    转为Bitmap

    RGB值转Bitmap
    代码如下:

    private Bitmap createColorBitmap(String rgb, int width, int height) {
          Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
          int color = Color.parseColor(rgb);
          bmp.eraseColor(color);
          return bmp;
    }

    //Usage
    Bitmap bmp = createColorBitmap("#cce8cf", 200, 50);

    Color值转Bitmap

    代码如下:

    private Bitmap createColorBitmap(int color, int width, int height) {
      Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
      bmp.eraseColor(color);
      return bmp;
    }
    //Usage
    Bitmap bmp = createColorBitmap(Color.BLUE, 200, 50);

    字节数组转Bitmap

    代码如下:

    private Bitmap getBitmapFromByteArray(byte[] array) {
      return BitmapFactory.decodeByteArray(array, 0, array.length);
    }

    读取文件转Bitmap

    代码如下:

    private Bitmap getBitmapFromFile(String pathName) {
          return BitmapFactory.decodeFile(pathName);
    }

    读取资源转Bitmap

    代码如下:

    private Bitmap getBitmapFromResource(Resources res, int resId) {
          return BitmapFactory.decodeResource(res, resId);
      }

    输入流转Bitmap

    代码如下:

    private Bitmap getBitmapFromStream(InputStream inputStream) {
          return BitmapFactory.decodeStream(inputStream);
    }

    Drawable转Bitmap

    代码如下:

    Bitmap icon = BitmapFactory.decodeResource(context.getResources(),R.drawable.icon_resource);

    转为Drawable

    资源转Drawable
    代码如下:

    Drawable drawable = getResources().getDrawable(R.drawable.ic_launcher);

    Bitmap转Drawable
    代码如下:

    Drawable d = new BitmapDrawable(getResources(),bitmap);

    图片圆角展示

    通过对图片数据bitmap进行处理即可,其中pixels为边角的半径。

    代码如下:

    public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int pixels) {
            Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap
                    .getHeight(), Config.ARGB_8888);
            Canvas canvas = new Canvas(output);

            final int color = 0xff424242;
            final Paint paint = new Paint();
            final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
            final RectF rectF = new RectF(rect);
            final float roundPx = pixels;

            paint.setAntiAlias(true);
            canvas.drawARGB(0, 0, 0, 0);
            paint.setColor(color);
            canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

            paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
            canvas.drawBitmap(bitmap, rect, rect, paint);

            return output;
        }

    一起学吧部分文章转载自互联网,供读者交流和学习,若有涉及作者版权等问题请及时与我们联系,以便更正、删除或按规定办理。感谢所有提供资讯的网站,欢迎各类媒体与一起学吧进行文章共享合作。

    广告
    广告
    广告