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

The following examples show how to use android.graphics.Bitmap#getPixel() . 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: BitmapProcessing.java    From Effects-Pro with MIT License 6 votes vote down vote up
public static Bitmap invert(Bitmap src) {
	Bitmap output = Bitmap.createBitmap(src.getWidth(), src.getHeight(), src.getConfig());
	int A, R, G, B;
	int pixelColor;
	int height = src.getHeight();
	int width = src.getWidth();

	for (int y = 0; y < height; y++) {
		for (int x = 0; x < width; x++) {
			pixelColor = src.getPixel(x, y);
			A = Color.alpha(pixelColor);

			R = 255 - Color.red(pixelColor);
			G = 255 - Color.green(pixelColor);
			B = 255 - Color.blue(pixelColor);

			output.setPixel(x, y, Color.argb(A, R, G, B));
		}
	}

	src.recycle();
	src = null;

	return output;
}
 
Example 2
Source File: BadgeAnimator.java    From BadgeView with Apache License 2.0 6 votes vote down vote up
private BitmapFragment[][] getFragments(Bitmap badgeBitmap, PointF center) {
    int width = badgeBitmap.getWidth();
    int height = badgeBitmap.getHeight();
    float fragmentSize = Math.min(width, height) / 6f;
    float startX = center.x - badgeBitmap.getWidth() / 2f;
    float startY = center.y - badgeBitmap.getHeight() / 2f;
    BitmapFragment[][] fragments = new BitmapFragment[(int) (height / fragmentSize)][(int) (width / fragmentSize)];
    for (int i = 0; i < fragments.length; i++) {
        for (int j = 0; j < fragments[i].length; j++) {
            BitmapFragment bf = new BitmapFragment();
            bf.color = badgeBitmap.getPixel((int) (j * fragmentSize), (int) (i * fragmentSize));
            bf.x = startX + j * fragmentSize;
            bf.y = startY + i * fragmentSize;
            bf.size = fragmentSize;
            bf.maxSize = Math.max(width, height);
            fragments[i][j] = bf;
        }
    }
    badgeBitmap.recycle();
    return fragments;
}
 
Example 3
Source File: DominantImageColor.java    From SaveInsta with Apache License 2.0 6 votes vote down vote up
public static String getDominantColorOfImage(Bitmap bitmap) {
    int width = bitmap.getWidth();
    int height = bitmap.getHeight();

    Map m = new HashMap();
    for (int i = 0; i < width; i++) {
        for (int j = 0; j < height; j++) {
            int rgb = bitmap.getPixel(i, j);
            int[] rgbArr = getRGBArr(rgb);
            // Filter out grays....
            if (!isGray(rgbArr)) {
                Integer counter = (Integer) m.get(rgb);
                if (counter == null)
                    counter = 0;
                counter++;
                m.put(rgb, counter);
            }
        }
    }
    return getMostCommonColour(m);
}
 
Example 4
Source File: BadgeAnimator.java    From BottomNavigationBar with Apache License 2.0 6 votes vote down vote up
private BitmapFragment[][] getFragments(Bitmap badgeBitmap, PointF center) {
    int width = badgeBitmap.getWidth();
    int height = badgeBitmap.getHeight();
    float fragmentSize = Math.min(width, height) / 6f;
    float startX = center.x - badgeBitmap.getWidth() / 2f;
    float startY = center.y - badgeBitmap.getHeight() / 2f;
    BitmapFragment[][] fragments = new BitmapFragment[(int) (height / fragmentSize)][(int) (width / fragmentSize)];
    for (int i = 0; i < fragments.length; i++) {
        for (int j = 0; j < fragments[i].length; j++) {
            BitmapFragment bf = new BitmapFragment();
            bf.color = badgeBitmap.getPixel((int) (j * fragmentSize), (int) (i * fragmentSize));
            bf.x = startX + j * fragmentSize;
            bf.y = startY + i * fragmentSize;
            bf.size = fragmentSize;
            bf.maxSize = Math.max(width, height);
            fragments[i][j] = bf;
        }
    }
    badgeBitmap.recycle();
    return fragments;
}
 
Example 5
Source File: ImageUtil.java    From droidddle with Apache License 2.0 6 votes vote down vote up
public static float calculateDarkness(Bitmap bitmap) {
    if (bitmap == null) {
        return 0;
    }

    int width = bitmap.getWidth();
    int height = bitmap.getHeight();

    int totalLum = 0;
    int n = 0;
    int x, y, color;
    for (y = 0; y < height; y++) {
        for (x = 0; x < width; x++) {
            ++n;
            color = bitmap.getPixel(x, y);
            totalLum += (0.21f * Color.red(color)
                    + 0.71f * Color.green(color)
                    + 0.07f * Color.blue(color));
        }
    }

    return (totalLum / n) / 256f;
}
 
Example 6
Source File: CustomModelActivity.java    From snippets-android with Apache License 2.0 6 votes vote down vote up
private float[][][][] bitmapToInputArray() {
    // [START mlkit_bitmap_input]
    Bitmap bitmap = getYourInputImage();
    bitmap = Bitmap.createScaledBitmap(bitmap, 224, 224, true);

    int batchNum = 0;
    float[][][][] input = new float[1][224][224][3];
    for (int x = 0; x < 224; x++) {
        for (int y = 0; y < 224; y++) {
            int pixel = bitmap.getPixel(x, y);
            // Normalize channel values to [-1.0, 1.0]. This requirement varies by
            // model. For example, some models might require values to be normalized
            // to the range [0.0, 1.0] instead.
            input[batchNum][x][y][0] = (Color.red(pixel) - 127) / 128.0f;
            input[batchNum][x][y][1] = (Color.green(pixel) - 127) / 128.0f;
            input[batchNum][x][y][2] = (Color.blue(pixel) - 127) / 128.0f;
        }
    }
    // [END mlkit_bitmap_input]

    return input;
}
 
Example 7
Source File: SlimeChunkRenderer.java    From blocktopograph with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Render a single chunk to provided bitmap (bm)
 * @param cm ChunkManager, provides chunks, which provide chunk-data
 * @param bm Bitmap to render to
 * @param dimension Mapped dimension
 * @param chunkX X chunk coordinate (x-block coord / Chunk.WIDTH)
 * @param chunkZ Z chunk coordinate (z-block coord / Chunk.LENGTH)
 * @param bX begin block X coordinate, relative to chunk edge
 * @param bZ begin block Z coordinate, relative to chunk edge
 * @param eX end block X coordinate, relative to chunk edge
 * @param eZ end block Z coordinate, relative to chunk edge
 * @param pX texture X pixel coord to start rendering to
 * @param pY texture Y pixel coord to start rendering to
 * @param pW width (X) of one block in pixels
 * @param pL length (Z) of one block in pixels
 * @return bm is returned back
 *
 * @throws Version.VersionException when the version of the chunk is unsupported.
 */
public Bitmap renderToBitmap(ChunkManager cm, Bitmap bm, Dimension dimension, int chunkX, int chunkZ, int bX, int bZ, int eX, int eZ, int pX, int pY, int pW, int pL) throws Version.VersionException {

    int x, z, i, j, tX, tY;

    MapType.OVERWORLD_SATELLITE.renderer.renderToBitmap(cm, bm, dimension, chunkX, chunkZ, bX, bZ, eX, eZ, pX, pY, pW, pL);

    boolean isSlimeChunk = isSlimeChunk(chunkX, chunkZ);
    int color, r, g, b, avg;

    //make slimeChunks much more green
    for (z = bZ, tY = pY ; z < eZ; z++, tY += pL) {
        for (x = bX, tX = pX; x < eX; x++, tX += pW) {
            color = bm.getPixel(tX, tY);
            r = (color >> 16) & 0xff;
            g = (color >> 8) & 0xff;
            b = color & 0xff;
            avg = (r + g + b) / 3;
            if(isSlimeChunk){
                r = b = avg;
                g = (g + 0xff) >> 1;
            } else {
                r = g = b = avg;
            }
            color = (color & 0xFF000000) | (r << 16) | (g << 8) | b;

            for(i = 0; i < pL; i++){
                for(j = 0; j < pW; j++){
                    bm.setPixel(tX + j, tY + i, color);
                }
            }

        }
    }

    return bm;
}
 
Example 8
Source File: Utility.java    From Bright with Apache License 2.0 5 votes vote down vote up
public static int[] getAverageColorRGB(Bitmap bitmap) {
    int R, G, B;
    int pixelColor;
    int width = bitmap.getWidth();
    int height = bitmap.getHeight();
    int size = width * height;

    R = G = B = 0;
    for (int x = 0; x < width; ++x) {
        for (int y = 0; y < height; ++y) {
            pixelColor = bitmap.getPixel(x, y);
            if (pixelColor == 0) {
                size--;
                continue;
            }
            R += Color.red(pixelColor);
            G += Color.green(pixelColor);
            B += Color.blue(pixelColor);
        }
    }

    R /= size;
    G /= size;
    B /= size;

    return (new int[]{ R, G, B });
}
 
Example 9
Source File: AndroidUtilities.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
public static int[] calcDrawableColor(Drawable drawable)
{
    int bitmapColor = 0xff000000;
    int result[] = new int[2];
    try
    {
        if (drawable instanceof BitmapDrawable)
        {
            Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
            if (bitmap != null)
            {
                Bitmap b = Bitmaps.createScaledBitmap(bitmap, 1, 1, true);
                if (b != null)
                {
                    bitmapColor = b.getPixel(0, 0);
                    if (bitmap != b)
                    {
                        b.recycle();
                    }
                }
            }
        }
        else if (drawable instanceof ColorDrawable)
        {
            bitmapColor = ((ColorDrawable) drawable).getColor();
        }
    }
    catch (Exception e)
    {
        FileLog.e(e);
    }

    double[] hsv = rgbToHsv((bitmapColor >> 16) & 0xff, (bitmapColor >> 8) & 0xff, bitmapColor & 0xff);
    hsv[1] = Math.min(1.0, hsv[1] + 0.05 + 0.1 * (1.0 - hsv[1]));
    hsv[2] = Math.max(0, hsv[2] * 0.65);
    int rgb[] = hsvToRgb(hsv[0], hsv[1], hsv[2]);
    result[0] = Color.argb(0x66, rgb[0], rgb[1], rgb[2]);
    result[1] = Color.argb(0x88, rgb[0], rgb[1], rgb[2]);
    return result;
}
 
Example 10
Source File: BitmapProcessing.java    From Effects-Pro with MIT License 5 votes vote down vote up
public static Bitmap cfilter(Bitmap src, double red, double green, double blue) {
	red = (double) red / 100;
	green = (double) green / 100;
	blue = (double) blue / 100;

	// image size
	int width = src.getWidth();
	int height = src.getHeight();
	// create output bitmap
	Bitmap bmOut = Bitmap.createBitmap(width, height, src.getConfig());
	// color information
	int A, R, G, B;
	int pixel;

	// scan through all pixels
	for(int x = 0; x < width; ++x) {
		for(int y = 0; y < height; ++y) {
			// get pixel color
			pixel = src.getPixel(x, y);
			// apply filtering on each channel R, G, B
			A = Color.alpha(pixel);
			R = (int)(Color.red(pixel) * red);
			G = (int)(Color.green(pixel) * green);
			B = (int)(Color.blue(pixel) * blue);
			// set new color pixel to output bitmap
			bmOut.setPixel(x, y, Color.argb(A, R, G, B));
		}
	}

	src.recycle();
	src = null;

	// return final image
	return bmOut;
}
 
Example 11
Source File: n.java    From stynico with MIT License 5 votes vote down vote up
/**
 * Extracts image pixels into byte array "pixels"
 */
protected void getImagePixels()
{
	int w = image.getWidth();
	int h = image.getHeight();
	//		int type = image.GetType().;
	if ((w != width)
		|| (h != height)
		) 
	{
		// create new image with right size/format
		Bitmap temp =Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
		Canvas canvas = new Canvas(temp);
		//图片居中
		canvas.drawBitmap(image, width / 2 - image.getWidth() / 2, height / 2 - image.getHeight() / 2, new Paint());
		image = temp;
	}
	/*
	 ToDo:
	 improve performance: use unsafe code 
	 */
	pixels = new int [ 3 * image.getWidth() * image.getHeight() ];
	int count = 0;
	Bitmap tempBitmap = Bitmap.createBitmap(image);
	for (int th = 0; th < image.getHeight(); th++)
	{
		for (int tw = 0; tw < image.getWidth(); tw++)
		{
			int color = tempBitmap.getPixel(tw, th);
			pixels[count] = Color.red(color);
			count++;
			pixels[count] = Color.green(color);
			count++;
			pixels[count] = Color.blue(color);
			count++;
		}
	}


}
 
Example 12
Source File: IcsColorDrawable.java    From CSipSimple with GNU General Public License v3.0 5 votes vote down vote up
public IcsColorDrawable(ColorDrawable drawable) {
    Bitmap bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888);
    Canvas c = new Canvas(bitmap);
    drawable.draw(c);
    this.color = bitmap.getPixel(0, 0);
    bitmap.recycle();
}
 
Example 13
Source File: BitmapText.java    From PD-classes with GNU General Public License v3.0 4 votes vote down vote up
protected void splitBy( Bitmap bitmap, int height, int color, String chars ) {
	
	autoUppercase = chars.equals( LATIN_UPPER );
	int length = chars.length();
	
	int width = bitmap.getWidth();
	float vHeight = (float)height / bitmap.getHeight();
	
	int pos;
	
spaceMeasuring:
	for (pos=0; pos <  width; pos++) {
		for (int j=0; j < height; j++) {
			if (bitmap.getPixel( pos, j ) != color) {
				break spaceMeasuring;
			}
		}
	}
	add( ' ', new RectF( 0, 0, (float)pos / width, vHeight ) );
	
	for (int i=0; i < length; i++) {
		
		char ch = chars.charAt( i );
		if (ch == ' ') {
			continue;
		} else {
			
			boolean found;
			int separator = pos;
			
			do {
				if (++separator >= width) {
					break;
				}
				found = true;
				for (int j=0; j < height; j++) {
					if (bitmap.getPixel( separator, j ) != color) {
						found = false;
						break;
					}
				}
			} while (!found);
			
			add( ch, new RectF( (float)pos / width, 0, (float)separator / width, vHeight ) );
			pos = separator + 1;
		}
	}
	
	lineHeight = baseLine = height( frames.get( chars.charAt( 0 ) ) );
}
 
Example 14
Source File: ImageView.java    From Carbon with Apache License 2.0 4 votes vote down vote up
@SuppressLint("MissingSuperCall")
@Override
public void draw(@NonNull Canvas canvas) {
    boolean r = revealAnimator != null;
    boolean c = !Carbon.isShapeRect(shapeModel, boundsRect);

    if (Carbon.IS_PIE_OR_HIGHER) {
        if (spotShadowColor != null)
            super.setOutlineSpotShadowColor(spotShadowColor.getColorForState(getDrawableState(), spotShadowColor.getDefaultColor()));
        if (ambientShadowColor != null)
            super.setOutlineAmbientShadowColor(ambientShadowColor.getColorForState(getDrawableState(), ambientShadowColor.getDefaultColor()));
    }

    if (isInEditMode() && (r || c) && getWidth() > 0 && getHeight() > 0) {
        Bitmap layer = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
        Canvas layerCanvas = new Canvas(layer);
        drawInternal(layerCanvas);

        Bitmap mask = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
        Canvas maskCanvas = new Canvas(mask);
        Paint maskPaint = new Paint(0xffffffff);
        maskCanvas.drawPath(cornersMask, maskPaint);

        for (int x = 0; x < getWidth(); x++) {
            for (int y = 0; y < getHeight(); y++) {
                int maskPixel = mask.getPixel(x, y);
                layer.setPixel(x, y, Color.alpha(maskPixel) > 0 ? layer.getPixel(x, y) : 0);
            }
        }
        canvas.drawBitmap(layer, 0, 0, paint);
    } else if (getWidth() > 0 && getHeight() > 0 && (((r || c) && !Carbon.IS_LOLLIPOP_OR_HIGHER) || !shapeModel.isRoundRect(boundsRect))) {
        int saveCount = canvas.saveLayer(0, 0, getWidth(), getHeight(), null, Canvas.ALL_SAVE_FLAG);

        if (r) {
            int saveCount2 = canvas.save();
            canvas.clipRect(revealAnimator.x - revealAnimator.radius, revealAnimator.y - revealAnimator.radius, revealAnimator.x + revealAnimator.radius, revealAnimator.y + revealAnimator.radius);
            drawInternal(canvas);
            canvas.restoreToCount(saveCount2);
        } else {
            drawInternal(canvas);
        }

        paint.setXfermode(Carbon.CLEAR_MODE);
        if (c) {
            cornersMask.setFillType(Path.FillType.INVERSE_WINDING);
            canvas.drawPath(cornersMask, paint);
        }
        if (r)
            canvas.drawPath(revealAnimator.mask, paint);
        paint.setXfermode(null);    // TODO check if this is needed

        canvas.restoreToCount(saveCount);
        paint.setXfermode(null);
    } else {
        drawInternal(canvas);
    }
}
 
Example 15
Source File: CsnA2.java    From contrib-drivers with Apache License 2.0 4 votes vote down vote up
/**
 * Returns bytes to print a bitmap in black-and-white. Any pixel on the bitmap that is not
 * transparent or white will be rendered as black on the printer. The bitmaps should not be
 * larger than 384 pixels.
 *
 * @param bitmap The bitmap to be printed.
 * @return Command to execute.
 */
public static byte[] commandPrintBitmap(@NonNull Bitmap bitmap) {
    final int BAND_HEIGHT = 24;

    int width = bitmap.getWidth();
    int height = bitmap.getHeight();

    ByteBuffer buffer = ByteBuffer.allocateDirect(width * 3 * (height / BAND_HEIGHT) * 10 + 3);
    // Send control bytes in big endian order.
    final byte[] controlByte = {(byte) (0x00ff & width), (byte) ((0xff00 & width) >> 8)};

    int[] pixels = new int[width * height];
    bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
    // Bands of pixels are sent that are 8 pixels high.  Iterate through bitmap
    // 24 rows of pixels at a time, capturing bytes representing vertical slices 1 pixel wide.
    // Each bit indicates if the pixel at that position in the slice should be dark or not.
    boolean[] isDark = new boolean[3];
    byte[] bandBytes = new byte[3];
    int[] pixelSlice = new int[3];
    float[] pixelSliceHsv = new float[3];
    for (int row = 0; row < height - 8; row += BAND_HEIGHT) {
        buffer.put(BITMAP_SET_LINE_SPACE_24);
        // Need to send these two sets of bytes at the beginning of each row.
        buffer.put(BITMAP_SELECT_BIT_IMAGE_MODE);
        buffer.put(controlByte);
        // Columns, unlike rows, are one at a time.
        for (int col = 0; col < width; col++) {
            // Reset the values of bandBytes for a new column
            bandBytes[0] = 0;
            bandBytes[1] = 0;
            bandBytes[2] = 0;
            // For each starting row/col position, evaluate each pixel in a column, or "band",
            // 24 pixels high.  Convert into 3 bytes.
            for (int rowOffset = 0; rowOffset < 8; rowOffset++) {
                // Because the printer only maintains correct height/width ratio
                // at the highest density, where it takes 24 bit-deep slices, process
                // a 24-bit-deep slice as 3 bytes.
                int pixel2Row = row + rowOffset + 8;
                int pixel3Row = row + rowOffset + 16;
                // If we go past the bottom of the image, just send white pixels so the printer
                // doesn't do anything.  Everything still needs to be sent in sets of 3 rows.
                pixelSlice[0] = bitmap.getPixel(col, row + rowOffset);
                pixelSlice[1] = (pixel2Row >= bitmap.getHeight()) ?
                        Color.TRANSPARENT : bitmap.getPixel(col, pixel2Row);
                pixelSlice[2] = (pixel3Row >= bitmap.getHeight()) ?
                        Color.TRANSPARENT : bitmap.getPixel(col, pixel3Row);

                for (int slice = 0; slice < 3; slice++) {
                    Color.colorToHSV(pixelSlice[slice], pixelSliceHsv);
                    isDark[slice] = pixelSliceHsv[2] < 25; // Hsv[2] -> Value should be 10% dark
                    if (Color.alpha(pixelSlice[slice]) < 25) {
                        isDark[slice] = false;
                    }
                    if (isDark[slice]) {
                        bandBytes[slice] |= 1 << (7 - rowOffset);
                    }
                }
            }
            // Write row's pixel data
            buffer.put(bandBytes);
        }
        // Finished row
        buffer.put(commandFeedLines((byte) 1));
    }
    // Finish image
    buffer.put(commandFeedLines((byte) 1));
    return buffer.array();
}
 
Example 16
Source File: EasyPaint.java    From geopaparazzi with GNU General Public License v3.0 4 votes vote down vote up
@Override
public boolean onTouchEvent(MotionEvent event) {
    LinePath linePath;
    int index;
    int id;
    int eventMasked = event.getActionMasked();
    switch (eventMasked) {
        case MotionEvent.ACTION_DOWN:
        case MotionEvent.ACTION_POINTER_DOWN: {
            index = event.getActionIndex();
            id = event.getPointerId(index);

            if (extractingColor) { //If the user chose the 'extract color' menu option, the touch event indicates where they want to extract the color from.
                extractingColor = false;

                View v = findViewById(R.id.CanvasId);
                v.setDrawingCacheEnabled(true);
                Bitmap cachedBitmap = v.getDrawingCache();

                int newColor = cachedBitmap.getPixel(Math.round(event.getX(index)), Math.round(event.getY(index)));

                v.destroyDrawingCache();
                colorChanged(newColor);

                Toast.makeText(getApplicationContext(),
                        R.string.color_extracted,
                        Toast.LENGTH_SHORT).show();
            } else {

                linePath = multiLinePathManager.addLinePathWithPointer(id);
                if (linePath != null) {
                    linePath.touchStart(event.getX(index), event.getY(index));
                } else {
                    Log.e("anupam", "Too many fingers!");
                }
            }

            break;
        }
        case MotionEvent.ACTION_MOVE:
            for (int i = 0; i < event.getPointerCount(); i++) {
                id = event.getPointerId(i);
                index = event.findPointerIndex(id);
                linePath = multiLinePathManager.findLinePathFromPointer(id);
                if (linePath != null) {
                    linePath.touchMove(event.getX(index), event.getY(index));
                }
                wasMadeDirty = true;
            }
            break;
        case MotionEvent.ACTION_UP:
        case MotionEvent.ACTION_POINTER_UP:
        case MotionEvent.ACTION_CANCEL:
            index = event.getActionIndex();
            id = event.getPointerId(index);
            linePath = multiLinePathManager.findLinePathFromPointer(id);
            if (linePath != null) {
                linePath.lineTo(linePath.getLastX(), linePath.getLastY());

                // Commit the path to our offscreen
                mCanvas.drawPath(linePath, mPaint);

                // Kill this so we don't double draw
                linePath.reset();

                // Allow this LinePath to be associated to another idPointer
                linePath.disassociateFromPointer();
            }
            wasMadeDirty = true;
            break;
    }
    invalidate();
    return true;
}
 
Example 17
Source File: GraphicsUtils.java    From Dashchan with Apache License 2.0 4 votes vote down vote up
@SuppressLint("RtlHardcoded")
public static int getDrawableColor(Context context, Drawable drawable, int gravity) {
	float density = ResourceUtils.obtainDensity(context);
	int size = Math.max(drawable.getMinimumWidth(), drawable.getMinimumHeight());
	if (size == 0) {
		size = (int) (64f * density);
	}
	Bitmap bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
	try {
		drawable.setBounds(0, 0, size, size);
		drawable.draw(new Canvas(bitmap));
		int x, y;
		switch (gravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
			case Gravity.LEFT: {
				x = 0;
				break;
			}
			case Gravity.RIGHT: {
				x = size - 1;
				break;
			}
			default: {
				x = size / 2;
				break;
			}
		}
		switch (gravity & Gravity.VERTICAL_GRAVITY_MASK) {
			case Gravity.TOP: {
				y = 0;
				break;
			}
			case Gravity.BOTTOM: {
				y = size - 1;
				break;
			}
			default: {
				y = size / 2;
				break;
			}
		}
		return bitmap.getPixel(x, y);
	} finally {
		bitmap.recycle();
	}
}
 
Example 18
Source File: ImageDsicern.java    From VMLibrary with Apache License 2.0 4 votes vote down vote up
/**
 * 检查像素点
 *
 * @param x         像素点x坐标
 * @param y         像素点y坐标
 * @param oneBitmap 第一个 bitmap 图片数据
 * @param twoBitmap 第二个 bitmap 图片数据
 * @return
 */
private static boolean checkPixel(int x, int y, Bitmap oneBitmap, Bitmap twoBitmap) {
    int onePixel = oneBitmap.getPixel(x, y);
    int twoPixel = twoBitmap.getPixel(x, y);
    if (onePixel == twoPixel) {
        return true;
    }
    return false;
}
 
Example 19
Source File: UtilsImage.java    From thermalprinterhelper with Apache License 2.0 4 votes vote down vote up
public static byte[] decodeBitmap(Bitmap bmp){
    int bmpWidth = bmp.getWidth();
    int bmpHeight = bmp.getHeight();

    List<String> list = new ArrayList<String>(); //binaryString list
    StringBuffer sb;


    int bitLen = bmpWidth / 8;
    int zeroCount = bmpWidth % 8;

    String zeroStr = "";
    if (zeroCount > 0) {
        bitLen = bmpWidth / 8 + 1;
        for (int i = 0; i < (8 - zeroCount); i++) {
            zeroStr = zeroStr + "0";
        }
    }

    for (int i = 0; i < bmpHeight; i++) {
        sb = new StringBuffer();
        for (int j = 0; j < bmpWidth; j++) {
            int color = bmp.getPixel(j, i);

            int r = (color >> 16) & 0xff;
            int g = (color >> 8) & 0xff;
            int b = color & 0xff;

            // if color close to white,bit='0', else bit='1'
            if (r > 160 && g > 160 && b > 160)
                sb.append("0");
            else
                sb.append("1");
        }
        if (zeroCount > 0) {
            sb.append(zeroStr);
        }
        list.add(sb.toString());
    }

    List<String> bmpHexList = binaryListToHexStringList(list);
    String commandHexString = "1D763000";
    String widthHexString = Integer
            .toHexString(bmpWidth % 8 == 0 ? bmpWidth / 8
                    : (bmpWidth / 8 + 1));
    if (widthHexString.length() > 2) {
        Log.e("decodeBitmap error", " width is too large");
        return null;
    } else if (widthHexString.length() == 1) {
        widthHexString = "0" + widthHexString;
    }
    widthHexString = widthHexString + "00";

    String heightHexString = Integer.toHexString(bmpHeight);
    if (heightHexString.length() > 2) {
        Log.e("decodeBitmap error", " height is too large");
        return null;
    } else if (heightHexString.length() == 1) {
        heightHexString = "0" + heightHexString;
    }
    heightHexString = heightHexString + "00";

    List<String> commandList = new ArrayList<String>();
    commandList.add(commandHexString+widthHexString+heightHexString);
    commandList.addAll(bmpHexList);

    return hexList2Byte(commandList);
}
 
Example 20
Source File: SimulationPageAnim.java    From HaoReader with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 绘制翻起页背面
 */
private void drawCurrentBackArea(Canvas canvas, Bitmap bitmap) {
    int i = (int) (mBezierStart1.x + mBezierControl1.x) / 2;
    float f1 = Math.abs(i - mBezierControl1.x);
    int i1 = (int) (mBezierStart2.y + mBezierControl2.y) / 2;
    float f2 = Math.abs(i1 - mBezierControl2.y);
    float f3 = Math.min(f1, f2);
    mPath1.reset();
    mPath1.moveTo(mBezierVertex2.x, mBezierVertex2.y);
    mPath1.lineTo(mBezierVertex1.x, mBezierVertex1.y);
    mPath1.lineTo(mBezierEnd1.x, mBezierEnd1.y);
    mPath1.lineTo(mTouchX, mTouchY);
    mPath1.lineTo(mBezierEnd2.x, mBezierEnd2.y);
    mPath1.close();
    GradientDrawable mFolderShadowDrawable;
    int left;
    int right;
    if (mIsRTandLB) {
        left = (int) (mBezierStart1.x - 1);
        right = (int) (mBezierStart1.x + f3 + 1);
        mFolderShadowDrawable = mFolderShadowDrawableLR;
    } else {
        left = (int) (mBezierStart1.x - f3 - 1);
        right = (int) (mBezierStart1.x + 1);
        mFolderShadowDrawable = mFolderShadowDrawableRL;
    }
    canvas.save();
    try {
        canvas.clipPath(mPath0);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            canvas.clipPath(mPath1);
        } else {
            canvas.clipPath(mPath1, Region.Op.INTERSECT);
        }
    } catch (Exception ignored) {
    }

    //对Bitmap进行取色
    int color = bitmap.getPixel(ScreenUtils.dpToPx(10), ScreenUtils.dpToPx(10));
    canvas.drawColor(color);

    canvas.rotate(mDegrees, mBezierStart1.x, mBezierStart1.y);
    mFolderShadowDrawable.setBounds(left, (int) mBezierStart1.y, right,
            (int) (mBezierStart1.y + mMaxLength));
    mFolderShadowDrawable.draw(canvas);
    canvas.restore();
}