android画图------字节数组转化为图片

在这个例程当中,主要讲了将一个图片压缩成字节流,然后转化成数组 在变成图片的故事。
首先 图片压缩成流 在转变成图片的方法还是值得学习的:
  private static Bitmap codec(Bitmap src, Bitmap.CompressFormat format,
                                    int quality) {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            src.compress(format, quality, os);           

            byte[] array = os.toByteArray();
            return BitmapFactory.decodeByteArray(array, 0, array.length);
        }

初始化 图片:
mBitmaps = new Bitmap[6];
            // these three are initialized with colors[]
            mBitmaps[0] = Bitmap.createBitmap(colors, 0, STRIDE, WIDTH, HEIGHT,
                                              Bitmap.Config.ARGB_8888);
           mBitmaps[1] = Bitmap.createBitmap(colors, 0, STRIDE, WIDTH, HEIGHT,                                              Bitmap.Config.RGB_565);
            mBitmaps[2] = Bitmap.createBitmap(colors, 0, STRIDE, WIDTH, HEIGHT,
                                              Bitmap.Config.ARGB_4444);
           
            // these three will have their colors set later
            mBitmaps[3] = Bitmap.createBitmap(WIDTH, HEIGHT,
                                              Bitmap.Config.ARGB_8888);
            mBitmaps[4] = Bitmap.createBitmap(WIDTH, HEIGHT,
                                              Bitmap.Config.RGB_565);
            mBitmaps[5] = Bitmap.createBitmap(WIDTH, HEIGHT,
                                              Bitmap.Config.ARGB_4444);
            for (int i = 3; i <= 5; i++) {
                mBitmaps[i].setPixels(colors, 0, STRIDE, 0, 0, WIDTH, HEIGHT);
            }
           
for (int i = 0; i < mBitmaps.length; i++) {
                mJPEG[i] = codec(mBitmaps[i], Bitmap.CompressFormat.JPEG, 80);
                mPNG[i] = codec(mBitmaps[i], Bitmap.CompressFormat.PNG, 0);

最后将图片绘画在屏幕上
  @Override protected void onDraw(Canvas canvas) {
            canvas.drawColor(Color.WHITE);

            for (int i = 0; i < mBitmaps.length; i++) {
                canvas.drawBitmap(mBitmaps[i], 0, 0, null);
                canvas.drawBitmap(mJPEG[i], 80, 0, null);
                canvas.drawBitmap(mPNG[i], 160, 0, null);
                canvas.translate(0, mBitmaps[i].getHeight());
            }
           
            // draw the color array directly, w/o craeting a bitmap object
            canvas.drawBitmap(mColors, 0, STRIDE, 0, 0, WIDTH, HEIGHT,
                              true, null);
            canvas.translate(0, HEIGHT);
            canvas.drawBitmap(mColors, 0, STRIDE, 0, 0, WIDTH, HEIGHT,
                              false, mPaint);
        }
上面的绘制 有三种情况 绘制jpeg 绘制png 直接绘制原数组。
mBitmaps[i].setPixels(colors, 0, STRIDE, 0, 0, WIDTH, HEIGHT);
也可以通过上面的方式来改变颜色

你可能感兴趣的:(android,OS)