Java Code Examples for android.graphics.Bitmap#setPixels()

The following examples show how to use android.graphics.Bitmap#setPixels() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MosaicUtil.java    From PhotoEdit with Apache License 2.0 6 votes vote down vote up
/**
 * 模糊效果
 * 
 * @param bitmap
 *            原图像
 * 
 * @return 模糊图像
 */
public static Bitmap getBlur(Bitmap bitmap)
{
	int iterations = 1;
	int radius = 8;
	int width = bitmap.getWidth();
	int height = bitmap.getHeight();
	int[] inPixels = new int[width * height];
	int[] outPixels = new int[width * height];
	Bitmap blured = Bitmap.createBitmap(width, height,
			Config.ARGB_8888);
	bitmap.getPixels(inPixels, 0, width, 0, 0, width, height);
	for (int i = 0; i < iterations; i++)
	{
		blur(inPixels, outPixels, width, height, radius);
		blur(outPixels, inPixels, height, width, radius);
	}
	blured.setPixels(inPixels, 0, width, 0, 0, width, height);
	return blured;
}
 
Example 2
Source File: BlurUtils.java    From LLApp with Apache License 2.0 6 votes vote down vote up
/**
 *
 * @param sentBitmap  位图对象
 * @param radius  模糊度
 * @return  drawable
 */
public static Drawable BoxBlurFilter(Bitmap sentBitmap,float radius) {
    //先处理原图,根据ImageView的大小进行压缩一下
    hRadius = vRadius = radius;
    if(sentBitmap.getWidth()>1000||sentBitmap.getHeight()>1000){
        sentBitmap = Bitmap.createScaledBitmap(sentBitmap, sentBitmap.getWidth()/3, sentBitmap.getHeight()/3, false);
        sentBitmap = sentBitmap.copy(sentBitmap.getConfig(), true);
    }
    int width = sentBitmap.getWidth();
    int height = sentBitmap.getHeight();
    int[] inPixels = new int[width * height];
    int[] outPixels = new int[width * height];
    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    sentBitmap.getPixels(inPixels, 0, width, 0, 0, width, height);
    for (int i = 0;
         i < iterations; i++) {
        blur(inPixels, outPixels, width, height, hRadius);
        blur(outPixels, inPixels, height, width, vRadius);
    }
    blurFractional(inPixels, outPixels, width, height, hRadius);
    blurFractional(outPixels, inPixels, height, width, vRadius);
    bitmap.setPixels(inPixels, 0, width, 0, 0, width, height);
    Drawable drawable = new BitmapDrawable(bitmap);
    return drawable;
}
 
Example 3
Source File: EncodingHandler.java    From CodeScaner with MIT License 6 votes vote down vote up
public static Bitmap createQRCode(String str,int widthAndHeight) throws WriterException {
	Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
       hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
	BitMatrix matrix = new MultiFormatWriter().encode(str,
			BarcodeFormat.QR_CODE, widthAndHeight, widthAndHeight);
	int width = matrix.getWidth();
	int height = matrix.getHeight();
	int[] pixels = new int[width * height];
	
	for (int y = 0; y < height; y++) {
		for (int x = 0; x < width; x++) {
			if (matrix.get(x, y)) {
				pixels[y * width + x] = BLACK;
			}
		}
	}
	Bitmap bitmap = Bitmap.createBitmap(width, height,
			Bitmap.Config.ARGB_8888);
	bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
	return bitmap;
}
 
Example 4
Source File: BitmapUtil.java    From Android-Architecture with Apache License 2.0 6 votes vote down vote up
/**
 * 将彩色图转换为灰度图
 *
 * @param img
 * @return
 */
public static Bitmap convertGreyImg(Bitmap img) {
    int width = img.getWidth(); // 获取位图的宽
    int height = img.getHeight(); // 获取位图的高

    int[] pixels = new int[width * height]; // 通过位图的大小创建像素点数组

    img.getPixels(pixels, 0, width, 0, 0, width, height);
    int alpha = 0xFF << 24;
    for (int i = 0; i < height; i++) {
        for (int j = 0; j < width; j++) {
            int grey = pixels[width * i + j];

            int red = ((grey & 0x00FF0000) >> 16);
            int green = ((grey & 0x0000FF00) >> 8);
            int blue = (grey & 0x000000FF);

            grey = (int) ((float) red * 0.3 + (float) green * 0.59 + (float) blue * 0.11);
            grey = alpha | (grey << 16) | (grey << 8) | grey;
            pixels[width * i + j] = grey;
        }
    }
    Bitmap result = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
    result.setPixels(pixels, 0, width, 0, 0, width, height);
    return result;
}
 
Example 5
Source File: PaymentRequestFragment.java    From bitcoinpos with MIT License 6 votes vote down vote up
Bitmap encodeAsBitmap(String str, int size) throws WriterException {
    BitMatrix result;
    try {
        result = new MultiFormatWriter().encode(str, BarcodeFormat.QR_CODE, size, size);
    } catch (IllegalArgumentException iae) {
        // Unsupported format
        return null;
    }
    int width = result.getWidth();
    int height = result.getHeight();
    int[] pixels = new int[width * height];
    for (int y = 0; y < height; y++) {
        int offset = y * width;
        for (int x = 0; x < width; x++) {
            pixels[offset + x] = result.get(x, y) ? 0xFF000000 : 0xFFFFFFFF;
        }
    }
    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
    return bitmap;
}
 
Example 6
Source File: PlanarYUVLuminanceSource.java    From react-native-smart-barcode with MIT License 6 votes vote down vote up
public Bitmap renderCroppedGreyscaleBitmap() {
    int width = getWidth();
    int height = getHeight();
    int[] pixels = new int[width * height];
    byte[] yuv = yuvData;
    int inputOffset = top * dataWidth + left;

    for (int y = 0; y < height; y++) {
      int outputOffset = y * width;
      for (int x = 0; x < width; x++) {
        int grey = 0;
        try {
          grey = yuv[inputOffset + x] & 0xff;
        } catch (ArrayIndexOutOfBoundsException e) {
//          Log.e("Exception","ArrayIndexOutOfBoundsException:"+e);
          e.printStackTrace();
        }
        pixels[outputOffset + x] = 0xFF000000 | (grey * 0x00010101);
      }
      inputOffset += dataWidth;
    }

    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
    return bitmap;
  }
 
Example 7
Source File: QRCodeEncoder.java    From zom-android-matrix with Apache License 2.0 5 votes vote down vote up
public Bitmap encodeAsBitmap() throws WriterException {
    if (!encoded) return null;

    Map<EncodeHintType, Object> hints = null;
    String encoding = guessAppropriateEncoding(contents);
    if (encoding != null) {
        hints = new EnumMap<>(EncodeHintType.class);
        hints.put(EncodeHintType.CHARACTER_SET, encoding);
    }
    MultiFormatWriter writer = new MultiFormatWriter();
    BitMatrix result = writer.encode(contents, format, dimension, dimension, hints);
    int width = result.getWidth();
    int height = result.getHeight();
    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);

    int[] pixels = new int[width * height];
    // All are 0, or black, by default
    for (int y = 0; y < height; y++) {
        int offset = y * width;
        for (int x = 0; x < width; x++) {
            pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
            //bitmap.setPixel(x,y,result.get(x, y) ? BLACK : WHITE);
        }
    }

    bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
    return bitmap;
}
 
Example 8
Source File: AbsCodec.java    From StarBarcode with Apache License 2.0 5 votes vote down vote up
@Override
public Bitmap encodeBarcode(String content, int widthPixel, int heightPixel) {

    if (TextUtils.isEmpty(content))
        throw new NullPointerException("The content of the QR code image cannot be empty");
    Map<EncodeHintType, Object> hintTypeMap = new EnumMap<>(EncodeHintType.class);
    hintTypeMap.put(EncodeHintType.CHARACTER_SET, "utf-8");
    //空白边距的宽度
    hintTypeMap.put(EncodeHintType.MARGIN, 0);
    //容错级别
    hintTypeMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
    try {
        //矩阵转换
        BitMatrix matrix = new MultiFormatWriter().encode(content, getEncodeFormat(), widthPixel, heightPixel, hintTypeMap);
        int[] pixels = new int[widthPixel * heightPixel];
        //使用二维码算法,逐个生成二维码的图片
        for (int y = 0; y < heightPixel; y++) {
            for (int x = 0; x < widthPixel; x++) {
                if (matrix.get(x, y)) {
                    pixels[y * widthPixel + x] = 0xff000000; //前景色
                } else {
                    pixels[y * widthPixel + x] = 0xffffffff; //背景色
                }
            }
        }
        final Bitmap bitmap = Bitmap.createBitmap(widthPixel, heightPixel, Bitmap.Config.ARGB_8888);
        bitmap.setPixels(pixels, 0, widthPixel, 0, 0, widthPixel, heightPixel);
        return bitmap;
    } catch (WriterException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 9
Source File: BitmapPixelUtil.java    From HideImageMaker with Apache License 2.0 5 votes vote down vote up
public static void 反相(Bitmap target) {
    final int width = target.getWidth(), height = target.getHeight();
    int[] targetPixels = new int[width * height];
    getBitmapPixelColor(target, (x, y, a, r, g, b) -> {
        int max = 255;
        targetPixels[x + y * width] = Color.argb(a, max - r, max - g, max - b);
    });
    target.setPixels(targetPixels, 0, width, 0, 0, width, height);
}
 
Example 10
Source File: DecodeHandler.java    From appinventor-extensions with Apache License 2.0 5 votes vote down vote up
private static Bitmap toBitmap(LuminanceSource source, int[] pixels) {
  int width = source.getWidth();
  int height = source.getHeight();
  Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
  bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
  return bitmap;
}
 
Example 11
Source File: ScanForResultActivity.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
private void decode(final byte[] data)
{
    final PlanarYUVLuminanceSource source = cameraManager.buildLuminanceSource(data);
    final BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));

    try {
        hints.put(DecodeHintType.NEED_RESULT_POINT_CALLBACK,
                  (ResultPointCallback) dot -> runOnUiThread(() -> scannerView.addDot(dot)));
        final Result scanResult = reader.decode(bitmap, hints);

        Log.d(TAG,"scanResult " + scanResult);
        final int thumbnailWidth = source.getThumbnailWidth();
        final int thumbnailHeight = source.getThumbnailHeight();
        final float thumbnailScaleFactor = (float) thumbnailWidth / source.getWidth();

        final Bitmap thumbnailImage = Bitmap.createBitmap(thumbnailWidth, thumbnailHeight,
                                                          Bitmap.Config.ARGB_8888);
        thumbnailImage.setPixels(
            source.renderThumbnail(), 0, thumbnailWidth, 0, 0, thumbnailWidth, thumbnailHeight);

        runOnUiThread(() -> handleResult(scanResult, thumbnailImage, thumbnailScaleFactor));
    } catch (final ReaderException x) {
        // retry
        cameraHandler.post(fetchAndDecodeRunnable);
    } finally {
        reader.reset();
    }
}
 
Example 12
Source File: GaussianFastBlur.java    From BlurView with Apache License 2.0 5 votes vote down vote up
@Override
public Bitmap blur(int radius, Bitmap original) {
    int w = original.getWidth();
    int h = original.getHeight();
    int[] pix = new int[w * h];
    original.getPixels(pix, 0, w, 0, 0, w, h);

    for(int r = radius; r >= 1; r /= 2) {
        for(int i = r; i < h - r; i++) {
            for(int j = r; j < w - r; j++) {
                int tl = pix[(i - r) * w + j - r];
                int tr = pix[(i - r) * w + j + r];
                int tc = pix[(i - r) * w + j];
                int bl = pix[(i + r) * w + j - r];
                int br = pix[(i + r) * w + j + r];
                int bc = pix[(i + r) * w + j];
                int cl = pix[i * w + j - r];
                int cr = pix[i * w + j + r];

                pix[(i * w) + j] = 0xFF000000 |
                        (((tl & 0xFF) + (tr & 0xFF) + (tc & 0xFF) + (bl & 0xFF) + (br & 0xFF) + (bc & 0xFF) + (cl & 0xFF) + (cr & 0xFF)) >> 3) & 0xFF |
                        (((tl & 0xFF00) + (tr & 0xFF00) + (tc & 0xFF00) + (bl & 0xFF00) + (br & 0xFF00) + (bc & 0xFF00) + (cl & 0xFF00) + (cr & 0xFF00)) >> 3) & 0xFF00 |
                        (((tl & 0xFF0000) + (tr & 0xFF0000) + (tc & 0xFF0000) + (bl & 0xFF0000) + (br & 0xFF0000) + (bc & 0xFF0000) + (cl & 0xFF0000) + (cr & 0xFF0000)) >> 3) & 0xFF0000;
            }
        }
    }
    original.setPixels(pix, 0, w, 0, 0, w, h);
    return original;
}
 
Example 13
Source File: QRCodeEncoder.java    From zxingfragmentlib with Apache License 2.0 5 votes vote down vote up
Bitmap encodeAsBitmap() throws WriterException {
  String contentsToEncode = contents;
  if (contentsToEncode == null) {
    return null;
  }
  Map<EncodeHintType,Object> hints = null;
  String encoding = guessAppropriateEncoding(contentsToEncode);
  if (encoding != null) {
    hints = new EnumMap<>(EncodeHintType.class);
    hints.put(EncodeHintType.CHARACTER_SET, encoding);
  }
  BitMatrix result;
  try {
    result = new MultiFormatWriter().encode(contentsToEncode, format, dimension, dimension, hints);
  } catch (IllegalArgumentException iae) {
    // Unsupported format
    return null;
  }
  int width = result.getWidth();
  int height = result.getHeight();
  int[] pixels = new int[width * height];
  for (int y = 0; y < height; y++) {
    int offset = y * width;
    for (int x = 0; x < width; x++) {
      pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
    }
  }

  Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
  bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
  return bitmap;
}
 
Example 14
Source File: BitmapPixelUtil.java    From HideImageMaker with Apache License 2.0 5 votes vote down vote up
/**
     * 图层特效 效果等于PhotoShop中图层特效的线性减淡(增加)
     *
     * @param src    作用特效的bitmap
     * @param target 目标bitmap
     * @return 作用特效后的bitmap
     */
    public static Bitmap 线性减淡(Bitmap src, Bitmap target) {
        final int width = src.getWidth(), height = src.getHeight();
        int[] srcPixels = new int[width * height];
        final Bitmap result = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        getBitmapPixelColor(src, (x, y, a, r, g, b) -> {
            int dstR, dstG, dstB, dstPixelColor, resultA, resultR, resultG, resultB;
            dstPixelColor = target.getPixel(x, y);
            dstR = Color.red(dstPixelColor);
            dstG = Color.green(dstPixelColor);
            dstB = Color.blue(dstPixelColor);
            resultA = 255;
            resultR = r + dstR;
            resultG = g + dstG;
            resultB = b + dstB;
            if (resultR > 255)
                resultR = 255;
            if (resultG > 255)
                resultG = 255;
            if (resultB > 255)
                resultB = 255;
//                result.setPixel(x, y, Color.argb(resultA, resultR, resultG, resultB));
            srcPixels[x + y * width] = Color.argb(resultA, resultR, resultG, resultB);
        });
        result.setPixels(srcPixels, 0, width, 0, 0, width, height);
        return result;
    }
 
Example 15
Source File: AnimUtils.java    From ifican with Apache License 2.0 5 votes vote down vote up
static Bitmap blurfast(Bitmap bmp, int radius) {
    try {
        Bitmap bitmap = bmp.copy(bmp.getConfig(), true);
        int w = bmp.getWidth();
        int h = bmp.getHeight();
        int[] pix = new int[w * h];
        bmp.getPixels(pix, 0, w, 0, 0, w, h);

        for(int r = radius; r >= 1; r /= 2) {
            for(int i = r; i < h - r; i++) {
                for(int j = r; j < w - r; j++) {
                    int tl = pix[(i - r) * w + j - r];
                    int tr = pix[(i - r) * w + j + r];
                    int tc = pix[(i - r) * w + j];
                    int bl = pix[(i + r) * w + j - r];
                    int br = pix[(i + r) * w + j + r];
                    int bc = pix[(i + r) * w + j];
                    int cl = pix[i * w + j - r];
                    int cr = pix[i * w + j + r];

                    pix[(i * w) + j] = 0xFF000000 |
                                               (((tl & 0xFF) + (tr & 0xFF) + (tc & 0xFF) + (bl & 0xFF) + (br & 0xFF) + (bc & 0xFF) + (cl & 0xFF) + (cr & 0xFF)) >> 3) & 0xFF |
                                               (((tl & 0xFF00) + (tr & 0xFF00) + (tc & 0xFF00) + (bl & 0xFF00) + (br & 0xFF00) + (bc & 0xFF00) + (cl & 0xFF00) + (cr & 0xFF00)) >> 3) & 0xFF00 |
                                               (((tl & 0xFF0000) + (tr & 0xFF0000) + (tc & 0xFF0000) + (bl & 0xFF0000) + (br & 0xFF0000) + (bc & 0xFF0000) + (cl & 0xFF0000) + (cr & 0xFF0000)) >> 3) & 0xFF0000;
                }
            }
        }
        bitmap.setPixels(pix, 0, w, 0, 0, w, h);
        return bitmap;
    }catch (Exception e) {
        return bmp;
    }
}
 
Example 16
Source File: ImageFilterUtils.java    From DevUtils with Apache License 2.0 4 votes vote down vote up
/**
 * 浮雕效果处理
 * @param bitmap 待操作源图片
 * @return 浮雕效果处理后的图片
 */
public static Bitmap emboss(final Bitmap bitmap) {
    if (bitmap == null) return null;
    try {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();

        int pixR = 0;
        int pixG = 0;
        int pixB = 0;

        int pixColor = 0;

        int newR = 0;
        int newG = 0;
        int newB = 0;

        int[] pixels = new int[width * height];
        bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
        int pos = 0;
        for (int i = 1, length = height - 1; i < length; i++) {
            for (int k = 1, len = width - 1; k < len; k++) {
                pos = i * width + k;
                pixColor = pixels[pos];

                pixR = Color.red(pixColor);
                pixG = Color.green(pixColor);
                pixB = Color.blue(pixColor);

                pixColor = pixels[pos + 1];
                newR = Color.red(pixColor) - pixR + 127;
                newG = Color.green(pixColor) - pixG + 127;
                newB = Color.blue(pixColor) - pixB + 127;

                newR = Math.min(255, Math.max(0, newR));
                newG = Math.min(255, Math.max(0, newG));
                newB = Math.min(255, Math.max(0, newB));

                pixels[pos] = Color.argb(255, newR, newG, newB);
            }
        }

        Bitmap newBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
        newBitmap.setPixels(pixels, 0, width, 0, 0, width, height);
        return newBitmap;
    } catch (Exception e) {
        LogPrintUtils.eTag(TAG, e, "emboss");
    }
    return null;
}
 
Example 17
Source File: QRCodeUtil.java    From GenerateQRCode with Apache License 2.0 4 votes vote down vote up
/**
 *  生成自定义二维码
 *
 * @param content                字符串内容
 * @param width                  二维码宽度
 * @param height                 二维码高度
 * @param character_set          编码方式(一般使用UTF-8)
 * @param error_correction_level 容错率 L:7% M:15% Q:25% H:35%
 * @param margin                 空白边距(二维码与边框的空白区域)
 * @param color_black            黑色色块
 * @param color_white            白色色块
 * @param logoBitmap             logo图片(传null时不添加logo)
 * @param logoPercent            logo所占百分比
 * @param bitmap_black           用来代替黑色色块的图片(传null时不代替)
 * @return
 */
public static Bitmap createQRCodeBitmap(String content, int width, int height, String character_set, String error_correction_level,
                                        String margin, int color_black, int color_white, Bitmap logoBitmap, float logoPercent, Bitmap bitmap_black) {
    // 字符串内容判空
    if (TextUtils.isEmpty(content)) {
        return null;
    }
    // 宽和高>=0
    if (width < 0 || height < 0) {
        return null;
    }
    try {
        /** 1.设置二维码相关配置,生成BitMatrix(位矩阵)对象 */
        Hashtable<EncodeHintType, String> hints = new Hashtable<>();
        // 字符转码格式设置
        if (!TextUtils.isEmpty(character_set)) {
            hints.put(EncodeHintType.CHARACTER_SET, character_set);
        }
        // 容错率设置
        if (!TextUtils.isEmpty(error_correction_level)) {
            hints.put(EncodeHintType.ERROR_CORRECTION, error_correction_level);
        }
        // 空白边距设置
        if (!TextUtils.isEmpty(margin)) {
            hints.put(EncodeHintType.MARGIN, margin);
        }
        /** 2.将配置参数传入到QRCodeWriter的encode方法生成BitMatrix(位矩阵)对象 */
        BitMatrix bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);

        /** 3.创建像素数组,并根据BitMatrix(位矩阵)对象为数组元素赋颜色值 */
        if (bitmap_black != null) {
            //从当前位图按一定的比例创建一个新的位图
            bitmap_black = Bitmap.createScaledBitmap(bitmap_black, width, height, false);
        }
        int[] pixels = new int[width * height];
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                //bitMatrix.get(x,y)方法返回true是黑色色块,false是白色色块
                if (bitMatrix.get(x, y)) {// 黑色色块像素设置
                    if (bitmap_black != null) {//图片不为null,则将黑色色块换为新位图的像素。
                        pixels[y * width + x] = bitmap_black.getPixel(x, y);
                    } else {
                        pixels[y * width + x] = color_black;
                    }
                } else {
                    pixels[y * width + x] = color_white;// 白色色块像素设置
                }
            }
        }

        /** 4.创建Bitmap对象,根据像素数组设置Bitmap每个像素点的颜色值,并返回Bitmap对象 */
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);

        /** 5.为二维码添加logo图标 */
        if (logoBitmap != null) {
            return addLogo(bitmap, logoBitmap, logoPercent);
        }
        return bitmap;
    } catch (WriterException e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 18
Source File: XBitmapUtils.java    From XFrame with Apache License 2.0 4 votes vote down vote up
/**
 * 柔化效果处理
 *
 * @param bitmap 原图
 * @return 柔化效果处理后的图片
 */
public static Bitmap soften(Bitmap bitmap) {
    // 高斯矩阵
    int[] gauss = new int[]{1, 2, 1, 2, 4, 2, 1, 2, 1};

    int width = bitmap.getWidth();
    int height = bitmap.getHeight();
    Bitmap newBitmap = Bitmap.createBitmap(width, height,
            Config.RGB_565);

    int pixR = 0;
    int pixG = 0;
    int pixB = 0;

    int pixColor = 0;

    int newR = 0;
    int newG = 0;
    int newB = 0;

    int delta = 16; // 值越小图片会越亮,越大则越暗

    int idx = 0;
    int[] pixels = new int[width * height];
    bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
    for (int i = 1, length = height - 1; i < length; i++) {
        for (int k = 1, len = width - 1; k < len; k++) {
            idx = 0;
            for (int m = -1; m <= 1; m++) {
                for (int n = -1; n <= 1; n++) {
                    pixColor = pixels[(i + m) * width + k + n];
                    pixR = Color.red(pixColor);
                    pixG = Color.green(pixColor);
                    pixB = Color.blue(pixColor);

                    newR = newR + (int) (pixR * gauss[idx]);
                    newG = newG + (int) (pixG * gauss[idx]);
                    newB = newB + (int) (pixB * gauss[idx]);
                    idx++;
                }
            }

            newR /= delta;
            newG /= delta;
            newB /= delta;

            newR = Math.min(255, Math.max(0, newR));
            newG = Math.min(255, Math.max(0, newG));
            newB = Math.min(255, Math.max(0, newB));

            pixels[i * width + k] = Color.argb(255, newR, newG, newB);

            newR = 0;
            newG = 0;
            newB = 0;
        }
    }

    newBitmap.setPixels(pixels, 0, width, 0, 0, width, height);
    return newBitmap;
}
 
Example 19
Source File: LSBWatermarkTask.java    From AndroidWM with Apache License 2.0 4 votes vote down vote up
@Override
protected Bitmap doInBackground(AsyncTaskParams... params) {
    Bitmap backgroundBitmap = params[0].getBackgroundImg();
    WatermarkText watermarkText = params[0].getWatermarkText();
    Bitmap watermarkBitmap = params[0].getWatermarkImg();
    String watermarkString;

    if (backgroundBitmap == null) {
        listener.onFailure(ERROR_NO_BACKGROUND);
        return null;
    }

    // convert the watermark bitmap into a String.
    if (watermarkBitmap != null) {
        watermarkString = BitmapUtils.bitmapToString(watermarkBitmap);
    } else {
        watermarkString = watermarkText.getText();
    }

    if (watermarkString == null) {
        listener.onFailure(ERROR_NO_WATERMARKS);
        return null;
    }

    Bitmap outputBitmap = Bitmap.createBitmap(backgroundBitmap.getWidth(), backgroundBitmap.getHeight(),
            backgroundBitmap.getConfig());

    int[] backgroundPixels = getBitmapPixels(backgroundBitmap);
    int[] backgroundColorArray = pixel2ARGBArray(backgroundPixels);

    // convert the Sting into a binary string, and, replace the single digit number.
    // using the rebuilt pixels to create a new watermarked image.
    String watermarkBinary = stringToBinary(watermarkString);

    if (watermarkBitmap != null) {
        watermarkBinary = LSB_IMG_PREFIX_FLAG + watermarkBinary + LSB_IMG_SUFFIX_FLAG;
    } else {
        watermarkBinary = LSB_TEXT_PREFIX_FLAG + watermarkBinary + LSB_TEXT_SUFFIX_FLAG;
    }

    int[] watermarkColorArray = stringToIntArray(watermarkBinary);
    if (watermarkColorArray.length > backgroundColorArray.length) {
        listener.onFailure(ERROR_PIXELS_NOT_ENOUGH);
    } else {
        int chunkSize = watermarkColorArray.length;
        int numOfChunks = (int) Math.ceil((double) backgroundColorArray.length / chunkSize);
        for (int i = 0; i < numOfChunks - 1; i++) {
            int start = i * chunkSize;
            for (int j = 0; j < chunkSize; j++) {
                backgroundColorArray[start + j] = replaceSingleDigit(backgroundColorArray[start + j]
                        , watermarkColorArray[j]);
            }
        }

        for (int i = 0; i < backgroundPixels.length; i++) {
            int color = Color.argb(
                    backgroundColorArray[4 * i],
                    backgroundColorArray[4 * i + 1],
                    backgroundColorArray[4 * i + 2],
                    backgroundColorArray[4 * i + 3]
            );
            backgroundPixels[i] = color;
        }

        outputBitmap.setPixels(backgroundPixels, 0, backgroundBitmap.getWidth(), 0, 0,
                backgroundBitmap.getWidth(), backgroundBitmap.getHeight());

        return outputBitmap;

    }
    return null;
}
 
Example 20
Source File: PlatformBitmapFactory.java    From fresco with MIT License 4 votes vote down vote up
/**
 * Creates a bitmap with the specified width and height. Its initial density is determined from
 * the given DisplayMetrics.
 *
 * @param display Display metrics for the display this bitmap will be drawn on
 * @param colors The colors to write to the bitmap
 * @param offset The index of the first color to read from colors[]
 * @param stride The number of colors in pixels[] to skip between rows.
 * @param width The width of the bitmap
 * @param height The height of the bitmap
 * @param config The bitmap config to create
 * @param callerContext the Tag to track who create the Bitmap
 * @return a reference to the bitmap
 * @throws IllegalArgumentException if the width or height are <= 0
 * @throws TooManyBitmapsException if the pool is full
 * @throws java.lang.OutOfMemoryError if the Bitmap cannot be allocated
 */
public CloseableReference<Bitmap> createBitmap(
    DisplayMetrics display,
    int[] colors,
    int offset,
    int stride,
    int width,
    int height,
    Bitmap.Config config,
    @Nullable Object callerContext) {
  CloseableReference<Bitmap> bitmapRef =
      createBitmap(display, width, height, config, callerContext);
  Bitmap bitmap = bitmapRef.get();
  bitmap.setPixels(colors, offset, stride, 0, 0, width, height);
  return bitmapRef;
}