I am trying to write a method that will take a Bitmap and force it to a strict black and white image (no shades of grey).
I first pass the bitmap to a method that makes it greyscale using colormatrix:
public Bitmap toGrayscale(Bitmap bmpOriginal)
{
int width, height;
height = bmpOriginal.getHeight();
width = bmpOriginal.getWidth();
Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
Canvas c = new Canvas(bmpGrayscale);
Paint paint = new Paint();
ColorMatrix cm = new ColorMatrix();
cm.setSaturation(0);
ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
paint.setColorFilter(f);
c.drawBitmap(bmpOriginal, 0, 0, paint);
return bmpGrayscale;
}
that works nice and fast..
then i pass it to another method to force the greyscaled image to a 2 color image (black and white) this method works but obviously it is going through each pixel and that takes a long time:
public Bitmap toStrictBlackWhite(Bitmap bmp){
Bitmap imageOut = bmp;
int tempColorRed;
for(int y=0; y<bmp.getHeight(); y++){
for(int x=0; x<bmp.getWidth(); x++){
tempColorRed = Color.red(imageOut.getPixel(x,y));
Log.v(TAG, "COLOR: "+tempColorRed);
if(imageOut.getPixel(x,y) < 127){
imageOut.setPixel(x, y, 0xffffff);
}
else{
imageOut.setPixel(x, y, 0x000000);
}
}
}
return imageOut;
}
anyone know a faster more efficient way to do this?
Don't use getPixel() and setPixel().
Use getPixels() which will return a multidimensional array of all pixels. Do your operations locally on this array, then use setPixels() to set back the modified array. This will be significantly faster.
Have you tried something like converting it into a byte array (see the answer here)?
And, as I look into this, the Android reference for developers about Bitmap processing might help you as well.
Related
I'm trying to convert all the black pixels in one Bitmap (Created from an ImageView that was a PNG file)..
I've tried it in many ways but I still couldn't succeed in that.
Please help me I'm trying it for like 3 days straight...
A little example of my code:
headSkin.buildDrawingCache();
final Bitmap bmp = headSkin.getDrawingCache();
int w = bmp.getWidth();
int h = bmp.getHeight();
for (int x = 0; x < w; x++) {
for (int y = 0; y < h; y++) {
int color = bmp.getPixel(x, y);
// Shift your alpha component value to the red component's.
bmp.setPixel(x, y, Color.RED);
}
}
As you can see... I didn't even state an IF statement..
I just tried to make all the pixels red in this bitmap and even this didn't work.. pls help?
I see 2 problems here,
First, you have this Bitmap object in your memory, and you change the black pixels to red, but how do you know if it is changed or not? You should set an ImageView to this Bitmap to see the result (or save it to file etc.)
Second, use getPixels and setPixels instead, getPixels will give you 1 dimensional array, it goes like 1.row, 2.row, 3.row etc. And setPixels also accepts a 1 dimensional array. This function is incredibly faster than altering pixels 1 by 1.
#Anil
Hi dude, just tried it and I can't use it 'cuz of IndexOutOfBound exception...
headSkin.buildDrawingCache();
bmp = headSkin.getDrawingCache();
int [] allpixels = new int [bmp.getHeight()*bmp.getWidth()];
bmp.getPixels(allpixels, 0, bmp.getWidth(), 0, 0, bmp.getWidth(), bmp.getHeight());
for(int i = 0; i < allpixels.length; i++)
{
if(allpixels[i] == Color.BLACK)
{
allpixels[i] = Color.RED;
}
}
bmp.setPixels(allpixels, 0, bmp.getWidth(), 0, 0, bmp.getWidth(), bmp.getHeight());
headSkin.setImageBitmap(bmp);
what is the problem here?
EDIT: Just tried it now while running, not debugging and it doesn't even show me an error or something.. It just makes about 1-2 single pixels red in this whole bitmap
headSkin.buildDrawingCache();
final Bitmap bmp = headSkin.getDrawingCache();
I think you have problem on these lines. The rest of the code looks fine.
Maybe the bitmap is not initialized, so you only have a Bitmap reference, instead of Bitmap object with data inside.
Can you delete the bitmap part from your code and initialize Bitmap like this:
Bitmap myBitmap = Bitmap.createBitmap(500, 500, Bitmap.Config.RGB8888);
and then perform pixel operations like you did above, just set all the pixels to same color.
I trying to achieve water reflection effect on bitmap. As I saw some apps called water reflection. I know how to do the reflection of the image but the wave on the image is what making me confused on how it is done.
see this image for example
I did many apps on bitmap manipulation but this is quite hard to achieve.
So any idea on where to start. Just an idea to start can be helpful.
For any one needed, I tried some simple tricks to get as closer as water reflection effect. It is not great but it looks fine to me.
I used two methods
Bitmap reflection method (give bitmap as a parameter)
public static Bitmap Reflection(Bitmap imageBitmap) {
int width = imageBitmap.getWidth();
int height = imageBitmap.getHeight();
Matrix matrix = new Matrix();
matrix.preScale(1, -1);
Bitmap reflectionImage = Bitmap.createBitmap(imageBitmap, 0,
0, width, height , matrix, false);
Bitmap newbit=Bitmap.createScaledBitmap(reflectionImage, reflectionImage.getWidth()/8, reflectionImage.getHeight()/8, true);
Bitmap newbit1=Bitmap.createScaledBitmap(newbit, newbit.getWidth()*8, newbit.getHeight()*8, true);
Bitmap scalednew=Bitmap.createScaledBitmap(newbit1, width, height-(height/4), true);
Bitmap newscaledone=overlay(scalednew);
reflectionImage=newscaledone;
Bitmap reflectedBitmap = Bitmap.createBitmap(width,
(height + height), Config.ARGB_8888);
Canvas canvas = new Canvas(reflectedBitmap);
canvas.drawBitmap(imageBitmap, 0, 0, null);
Paint defaultPaint = new Paint();
canvas.drawRect(0, height, width, height, defaultPaint);
canvas.drawBitmap(reflectionImage, 0, height , null);
Paint paint = new Paint();
paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
canvas.drawRect(0, height, width, reflectedBitmap.getHeight()
, paint);
return reflectedBitmap;
}
Bitmap overlay method. I am taking a wave bitmap with some opacity to overlay on the reflected image. So that it may look like water.
Bitmap wavebitmap=BitmapFactory.decodeResource(getResources(), R.drawable.waves1);
private static Bitmap overlay( Bitmap bmp2) {
Bitmap bmp1=WaterReflectionMainActivity.wavebitmap;
Bitmap bmp1new =Bitmap.createScaledBitmap(bmp1, bmp2.getWidth(), bmp2.getHeight(), true);
Bitmap bmOverlay = Bitmap.createBitmap(bmp1new.getWidth(), bmp1new.getHeight(), bmp1new.getConfig());
Canvas canvas = new Canvas(bmOverlay);
canvas.drawBitmap(bmp2, new Matrix(), null);
canvas.drawBitmap(bmp1new, new Matrix(), null);
return bmOverlay;
}
Well this is my version of water effect, I know this looks shit.
So if anyone still got some better effect please share your code .
thank you
Tutorial related to this: http://www.xaraxone.com/webxealot/workbook34/page_4.htm
Also have a read at this question: Add water effect on bitmap android.
Have a read at both of them, i hope you will get an idea from this
You may also want to look through these: 1, 2, 3
This is just an idea but basically, what you need is to apply a deformation on the bottom part of the image, meaning that for each pixel on the bottom half, you compute a position to get it's color from the top picture.
Here's a pseudo code to give you a hint :
for (int x = 0; x < width; x++) {
for (int y = 0; y < img.height; y++) {
// Compute a position on the original image
// tweak the values heres to get the effect you want
sourceX = x + (int) (cos(10000.0 / y) * 20);
sourceY = img.height - y - 1 +(int)( sin(y* 0.5) * 20);
// Maybe check the range of sourceX and source Y
int color = img.getColor(sourceX, sourceY)
outptut.setColor(x, y + img.height, color);
}
}
you can achieve this by masking may this code will help you
http://www.seeques.com/22527681/how-can-do-this-effect-in-android-may-be-android-bitmap-masking-effect.html
EDIT
also see this for reference
http://code.google.com/p/android-ripple-demo/source/browse/#svn%2Ftrunk%2Fsrc%2Fcom%2Fkesalin%2FRippleDemo
https://github.com/esteewhy/whater
http://code.google.com/p/waterrippleeffect/source/browse/trunk/src/com/example/android/watereffect/WaterEffectView.java?r=3
android noise effect on bitmap
I want to combine many small bitmaps which are contained in ArrayList to one large bitmap.
However, I don't know why the large bitmap is looped. It means it seems to copy only the first element in the array. I tried to draw each small bitmap in the array to test and it works fine, but when I run the loop like the below code, it goes wrong.
In addiditon, when I add the bmp.recycle() and bmp = null, it causes the error "trying to use a recycled bitmap". I don't understand why the error happens.
Can you help me, please, thanks!
public static Bitmap getBitmapForVisibleRegion(WebView webview) {
Bitmap returnedBitmap = null;
webview.setDrawingCacheEnabled(true);
returnedBitmap = Bitmap.createBitmap(webview.getDrawingCache());
webview.setDrawingCacheEnabled(false);
return returnedBitmap;
}
public void CombineBitmap(){
ArrayList<Bitmap> bmps = new ArrayList<Bitmap>();
for (int i = 0; i < webView.getWidth; i+=needToCapture){
bmps.add(getBitmapForVisibleRegion(webView));
webView.scrollBy(needToCapture, 0);
}
Bitmap bigbitmap = Bitmap.createBitmap(largeBitmapWidth, largeBitmapHeight, Bitmap.Config.ARGB_8888);
Canvas bigcanvas = new Canvas(bigbitmap);
Paint paint = new Paint();
int iWidth = 0;
for (int i = 0; i < bmps.size(); i++) {
Bitmap bmp = bmps.get(i);
bigcanvas.drawBitmap(bmp, iWidth , 0, paint);
iWidth +=bmp.getWidth();
bmp.recycle();
bmp=null;
}
}
I finally found out my problem. It's because of my dummy mistake.
I have to use scrollTo instead scrollBy
After I change to scrollTo, everything works fine. This is really an useful experience.
According to the documentation of Bitmap.createBitmap(Bitmap),
Returns an immutable bitmap from the source bitmap. The new bitmap may be the same object as source, or a copy may have been made. It is initialized with the same density as the original bitmap.`
Therefore, replace
returnedBitmap = Bitmap.createBitmap(webview.getDrawingCache());
with
returnedBitmap = webview.getDrawingCache().copy(Config.ARGB_8888, false);
I have some question about water mark within android code!
Following code showed my idea about WaterMark!
However,It does not work normally.
e.g. only the image end with .png can be watered mark
Is there a scheme about water mark(.jpeg, .jpg, .wbmp, .bmp, .png or others)
protected static Bitmap getDrmPicture(Context context,String path){
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap originMap = BitmapFactory.decodeFile (path,options);
Bitmap waterMark = BitmapFactory.decodeResource(context.getResources(), R.drawable.close);
InputStream input;
byte[] b;
Bitmap waterMark = null;
try {
input = context.getResources().openRawResource(R.drawable.lock);
b = new byte[input.available()];
input.read(b);
waterMark = DecodeUtils.requestDecode(jc, b, null);
}catch(IOException e){
}
int w = originMap.getWidth();
int h = originMap.getHeight();
int ww = waterMark.getWidth();
int wh = waterMark.getHeight();
Bitmap newb = Bitmap.createBitmap(w, h,Bitmap.Config.ARGB_8888;);
Canvas cv = new Canvas(newb);
cv.drawBitmap(originMap, 0, 0, null);
cv.drawBitmap(waterMark, w - ww, h - wh, null);
cv.save(Canvas.ALL_SAVE_FLAG);
cv.restore();
return newb;
}
Thanks !
This is the code I use to apply watermark to a jpeg, it should work for you too,
public Bitmap applyWatermarkColorFilter(Drawable drawable) {
Bitmap image = ((BitmapDrawable)drawable).getBitmap();
Bitmap result = Bitmap.createBitmap(image.getWidth(), image.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(result);
canvas.drawBitmap(image, 0, 0, null);
Bitmap watermark = BitmapFactory.decodeResource(getResources(), R.drawable.watermark);
canvas.drawBitmap(watermark, image.getWidth()/2 - watermark.getWidth()/2,
image.getHeight()/2 - watermark.getHeight()/2,
null);
return result;
}
Basically after this u have to use Bitmap.compress(<arguments>) to get a jpg out of it.
Din't try for the other formats. May be it might be possible if you can extract the Bitmap out of them like how we do for jpg and png.
https://stackoverflow.com/questions/6756975/draw-multi-line-text-to-canvas
Measure height of multiline text
To center text vertically we need to know text height. Instantiate StaticLayout with text width according to your needs, for us it is simple the width of Bitmap/Canvas minus 16dp padding. The getHeight() then returns height of text.
Positioning text on Canvas
There are four simple steps to position text on Canvas:
Save the current matrix and clip with Canvas.save().
Apply translation to Canvas matrix with Canvas.translate(x,y).
Draw StaticLayout on Canvas with StaticLayout.draw(canvas).
Revert matrix translation with Canvas.restore() method.
I'm beating my head against a wall here, and I'm fairly certain I'm doing something stupid, so time to make my stupidity public.
I'm trying to take two images, blend them together into a third image using standard blending algorithms (Hardlight, softlight, overlay, multiply, etc).
Because Android does not have such blend properties build in, I've gone down the path of taking each pixel and combine them using an algorithm. However, the results are garbage. Below is the results of a simple multiply blend (images used, and expected result).
BASE:
BLEND:
EXPECTED RESULT:
GARBAGE RESULT:
Any help would be appreciated. Below is the code, which I've tried to strip out all the "junk", but some may have made it through. I'll clean it up if something isn't clear.
ImageView imageView = (ImageView) findViewById(R.id.ImageView01);
Bitmap base = BitmapFactory.decodeResource(getResources(), R.drawable.base);
Bitmap result = base.copy(Bitmap.Config.RGB_565, true);
Bitmap blend = BitmapFactory.decodeResource(getResources(), R.drawable.blend);
IntBuffer buffBase = IntBuffer.allocate(base.getWidth() * base.getHeight());
base.copyPixelsToBuffer(buffBase);
buffBase.rewind();
IntBuffer buffBlend = IntBuffer.allocate(blend.getWidth() * blend.getHeight());
blend.copyPixelsToBuffer(buffBlend);
buffBlend.rewind();
IntBuffer buffOut = IntBuffer.allocate(base.getWidth() * base.getHeight());
buffOut.rewind();
while (buffOut.position() < buffOut.limit()) {
int filterInt = buffBlend.get();
int srcInt = buffBase.get();
int redValueFilter = Color.red(filterInt);
int greenValueFilter = Color.green(filterInt);
int blueValueFilter = Color.blue(filterInt);
int redValueSrc = Color.red(srcInt);
int greenValueSrc = Color.green(srcInt);
int blueValueSrc = Color.blue(srcInt);
int redValueFinal = multiply(redValueFilter, redValueSrc);
int greenValueFinal = multiply(greenValueFilter, greenValueSrc);
int blueValueFinal = multiply(blueValueFilter, blueValueSrc);
int pixel = Color.argb(255, redValueFinal, greenValueFinal, blueValueFinal);
buffOut.put(pixel);
}
buffOut.rewind();
result.copyPixelsFromBuffer(buffOut);
BitmapDrawable drawable = new BitmapDrawable(getResources(), result);
imageView.setImageDrawable(drawable);
}
int multiply(int in1, int in2) {
return in1 * in2 / 255;
}
After reproducing, I think your issue has to do with manipulating the images in RGB565 mode. As discussed in this post, Bitmaps apparently need to be in ARGB8888 mode to manipulate properly. I first got the expected result on a multiply blend by doing the following:
Resources res = getResources();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap base = BitmapFactory.decodeResource(res, R.drawable.base, options);
Bitmap blend = BitmapFactory.decodeResource(res, R.drawable.blend, options);
// now base and blend are in ARGB8888 mode, which is what you want
Bitmap result = base.copy(Config.ARGB_8888, true);
// Continue with IntBuffers as before...
Converting the Bitmaps to ARGB8888 mode did seem to work for me, at least with the gradient test patterns. However, it you only need to do Screen or Multiply, you might try this as well:
// Same image creation/reading as above, then:
Paint p = new Paint();
p.setXfermode(new PorterDuffXfermode(Mode.MULTIPLY));
p.setShader(new BitmapShader(blend, TileMode.CLAMP, TileMode.CLAMP));
Canvas c = new Canvas();
c.setBitmap(result);
c.drawBitmap(base, 0, 0, null);
c.drawRect(0, 0, base.getWidth(), base.getHeight(), p);
With that, you aren't doing the per-pixel calculations, but you are limited to the preset PorterDuff.Modes. In my quick (and dirty) testing, this was the only way I was able to get the blending to work on non-gradient images.
Simple overlay you can do this way (for simplicity it is supposed that bmp1 is equal or bigger than bmp2):
private Bitmap bitmapOverlay(Bitmap bmp1, Bitmap bmp2)
{
Bitmap bmOverlay = Bitmap.createBitmap(bmp1.getWidth(), bmp1.getHeight(), bmp1.getConfig());
Canvas canvas = new Canvas(bmOverlay);
canvas.drawBitmap(bmp1, 0, 0, null);
canvas.drawBitmap(bmp2, 0, 0, null);
return bmOverlay;
}
For more complex blending algorithms, maybe you can help yourself with some available Bitmap/Canvas functions.