I made a bitmap class with a list of Pixels. The Pixel class has a position and a color. Now I am trying to get a bitmap from a BufferedImage.
This is the code I have tried:
private static Bitmap fromImage(BufferedImage image) {
Bitmap bitmap = new Bitmap();
for (int x = image.getMinX(); x < image.getWidth(); x++) {
for (int y = image.getMinY(); y < image.getHeight(); y++) {
bitmap.setPixel(new Pixel(RGBAColor.fromColor(
new Color(image.getRGB(x, y))), new Vector2(x, y)));
}
}
return bitmap;
}
public static Bitmap fromImage(String path) {
try {
BufferedImage img = ImageIO.read(Galaxy2D.class.getResource(
"/com/mcmastery/galaxy2d/resources/" + path));
BufferedImage conImg = new BufferedImage(img.getWidth(), img.getHeight(),
BufferedImage.TYPE_INT_ARGB);
conImg.createGraphics().drawImage(img, 0, 0, null);
return Bitmap.fromImage(conImg);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
It works, but when it paints the image to the screen it distorts it.
Original image: http://gyazo.com/0832ebf26f940b6dbf218e43101e63f8.png
Image painted to screen using bitmap methods: http://gyazo.com/c4b776f0e5fa0e54c167c10947582834.png
I have tried DataBufferInt too, and it still produces the same result. With other images, it just changes some pixel's positions to positions close to where they are supposed to be. But with the crosshair above, it turns it black and distorts it.
Not sure what a Bitmap is used for (I can't find it in the JDK7 API).
Maybe you can just use the getSubImage(...) method of the BufferedImage.
Related
I'm trying to draw a bunch of bitmaps vertically one below the other like this :
Original Bitmap :
Result expected :
Code :
int repeater = 4;
Bitmap bitmapTextSticker = ImageUtils.drawable2Bitmap(ResourceUtils.getDrawable(R.drawable.icon));
Bitmap background = Bitmap.createBitmap(bitmapTextSticker.getWidth(), bitmapTextSticker.getHeight() * repeater, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(background);
int top = 0;
for (int i = 0; i < repeater; i++) {
top = (i == 0 ? 0 : top + bitmapTextSticker.getHeight());
canvas.drawBitmap(bitmapTextSticker, 0f, top, null);
}
The above code is working, but the output is cropped.
I'm not sure if I'm missing something in your question, but all you have to do is change the top coordinate for each bitmap when calling drawBitmap(). In your specific code, just add:
top += height;
inside the for loop
Edit: from your updated question, it sounds like a Bitmap scaling issue, not a problem with position. Even your 1st bitmap is cropped. So, you should probably use a different canvas.drawbitmap() method:
public void drawBitmap (Bitmap bitmap, Rect src, RectF dst, Paint paint)
You can specify the dimensions of the destination Rect, which should let it scale properly. So, your code should be:
for(...){
...
RectF dest = new RectF(new Rect(0, top, bitmapTextSticker.getWidth(), bitmapTextSticker.getHeight()));
canvas.drawBitmap(bitmapTextSticker, null, dest, null);
}
The issue was I didn't set the density for the bitmap and the canvas :
ArrayList<Bitmap> bitmaps = new ArrayList<>();
for (int i = 0; i < repeater; i++) bitmaps.add(bmp);
int height = 0;
for (Bitmap map : bitmaps) height += map.getHeight();
Bitmap bitmap = Bitmap.createBitmap(bmp.getWidth(), height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.setDensity(DisplayMetrics.DENSITY_MEDIUM);
bitmap.setDensity(DisplayMetrics.DENSITY_MEDIUM);
int drawHeight = 0;
for (Bitmap map : bitmaps) {
if (map != null) {
canvas.drawBitmap(map, 0, drawHeight, null);
drawHeight += map.getHeight();
}
}
return bitmap;
I have a program that is supposed to take the RGB values of an image and then multiply them by some constants, and then draw the new image on a JPanel. The problem is that if my image is over a certain height, specifically over 187 pixels, the new colored image is different than an image with a height of less than 187px.
The JPanel shows this: example.
Notice how the longer recolored image is different than the shorter one. I'm sure that the shorter image's colors are correct, and I have no idea how it's getting messed up.
public class RecolorImage extends JPanel {
public static int scale = 3;
public static BufferedImage walk, walkRecolored;
public static BufferedImage shortWalk, shortWalkRecolored;
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(200*scale, 400*scale);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new RecolorImage());
walk = ImageLoader.loadImage("/playerWalk.png");
walkRecolored = recolor(walk);
shortWalk = ImageLoader.loadImage("/playerWalkShort.png");
shortWalkRecolored = recolor(shortWalk);
frame.setVisible(true);
}
#Override
public void paint(Graphics graphics) {
Graphics2D g = (Graphics2D) graphics;
g.scale(scale, scale);
g.drawImage(walk, 10, 10, null);
g.drawImage(walkRecolored, 40, 10, null);
g.drawImage(shortWalk, 70, 10, null);
g.drawImage(shortWalkRecolored, 100, 10, null);
}
The recolor method:
public static BufferedImage recolor(BufferedImage image) {
BufferedImage outputImage = deepCopy(image);
for (int y = 0; y < image.getHeight(); y++) {
for (int x = 0; x < image.getWidth(); x++) {
int rgb = image.getRGB(x, y);
Color c = new Color(rgb);
int r = c.getRed();
int g = c.getGreen();
int b = c.getBlue();
r *= 0.791;
g *= 0.590;
b *= 0.513;
int newRGB = (rgb & 0xff000000) | (r << 16) | (g << 8) | b;
outputImage.setRGB(x, y, newRGB);
}
}
return outputImage;
}
How I load the images and make deep copies:
public static BufferedImage loadImage(String path) {
try {
return ImageIO.read(ImageLoader.class.getResource(path));
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static BufferedImage deepCopy(BufferedImage image) {
ColorModel colorModel = image.getColorModel();
boolean isAlphaPremultiplied = colorModel.isAlphaPremultiplied();
WritableRaster raster = image.copyData(null);
return new BufferedImage(colorModel, raster, isAlphaPremultiplied, null);
}
My original images: the tall image and short image. Thanks for any help!
Your source images have different color models:
the short image uses 4 bytes per pixel (RGB and alpha)
the tall image uses 1 byte per pixel (index into a palette of 256 colors)
Your recolored images use the same color model as the source images (thanks to the deepCopy method), therefore the recolored image for the tall image also uses the same color palette as the source image, meaning that it cannot contain all the colors you want.
Since your recoloring code overwrites each pixel of the output image anyway the deep copy operation is unnecessary. Instead you would better create a full color image as target image like this:
public static BufferedImage recolor(BufferedImage image) {
BufferedImage outputImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
//... code as before
}
I'm trying to make a Mario game clone, and right now, in my constructor, I have a method that is supposed to make a certain color transparent instead of the current pinkish (R: 255, G: 0, B: 254). According to Photoshop, the hex value is ff00fe. My method is:
public Mario(){
this.state = MarioState.SMALL;
this.x = 54;
this.y = 806;
URL spriteAtLoc = getClass().getResource("sprites/Mario/SmallStandFaceRight.bmp");
try{
sprite = ImageIO.read(spriteAtLoc);
int width = sprite.getWidth();
int height = sprite.getHeight();
int[] pixels = new int[width * height];
sprite.getRGB(0, 0, width, height, pixels, 0, width);
for (int i = 0; i < pixels.length; i++) {
if (pixels[i] == 0xFFff00fe) {
pixels[i] = 0x00ff00fe; //this is supposed to set alpha value to 0 and make the target color transparent
}
}
} catch(IOException e){
System.out.println("sprite not found");
e.printStackTrace();
}
}
it runs and compiles, but sprite comes out exactly the same when I render it. (edit: perhaps of note I do not have super.paintComponent(g) in my paintComponent(g) method. The sprites are .bmps.
You are only retrieving the pixels using BufferedImage.getRGB. That returns a copy of the data in a certain area of the BufferedImage.
Any change you make to the int[] returned is not automatically reflected back into the image.
To update the image, you need to call BufferedImage.setRGB after you change the int[]:
sprite.setRGB(0, 0, width, height, pixels, 0, width);
Another change you should probably make (and this involves a little guesswork as I don't have your bmp to test with) - the BufferedImage returned by ImageIO.read may have type BufferedImage.TYPE_INT_RGB - meaning that it doesn't have an alpha channel. You can verify by printing sprite.getType(), if that prints 1 it's TYPE_INT_RGB without an alpha channel.
To get an alpha channel, create a new BufferedImage of the right size and then set the converted int[] on that image, then use the new image from then on:
BufferedImage newSprite = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
newSprite.setRGB(0, 0, width, height, pixels, 0, width);
sprite = newSprite; // Swap the old sprite for the new one with an alpha channel
BMP images don't provide an alpha channel, you have to set it manually (as you do in your code)...
when you check your pixel to have a certain color you have to check without alpha (BMP has no alpha it's always 0x0).
if (pixels[i] == 0x00ff00fe) { //THIS is the color WITHOUT alpha
pixels[i] = 0xFFff00fe; //set alpha to 0xFF to make this pixel transparent
}
so in short: you did all right but mixed it up a bit ^^
This works:
private BufferedImage switchColors(BufferedImage img) {
int w = img.getWidth();
int h = img.getHeight();
BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
// top left pixel is presumed to be BG color
int rgb = img.getRGB(0, 0);
for (int xx=0; xx<w; xx++) {
for (int yy=0; yy<h; yy++) {
int rgb2 = img.getRGB(xx, yy);
if (rgb2!=rgb) {
bi.setRGB(xx, yy, rgb2);
}
}
}
return bi;
}
I have this method to generate a Barcode bitmap:
public static Bitmap encodeToQrCode(String text, int width, int height) {
QRCodeWriter writer = new QRCodeWriter();
BitMatrix matrix = null;
try {
matrix = writer.encode(text, BarcodeFormat.QR_CODE, 400, 400);
} catch (WriterException ex) {
ex.printStackTrace();
}
Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height - 1; y++) {
bmp.setPixel(x, y, matrix.get(x, y) ? Color.BLACK : Color.WHITE);
}
}
return bmp;
}
Is there any way to find out that the Barcode has been scanned? I'm using zxing.
If I understand you correctly you're looking for a way to
Create a bitmap that contains a QR code
Display that bitmap on your device
Detect when a different device that doesn't use your software scans that code
This is not possible. The QR code bitmap is just that: A bitmap your app displays. And a barcode scanner app simply takes a photo of your display and tries to find patterns in that bitmap.
I am currently trying to read in an image pixel by pixel and change each colored pixel to the rgb value of (100,100,100). For whatever reason when I check the values of each pixel one the image is saved it has all the colored pixels as (46,46,46) instead.
Here is the original image
After running my program this is the image it gives to me
Here is the code
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Cmaps {
public static void main(String[] args){
File originalImage = new File("C:\\Users\\Me\\Desktop\\0005.bmp");
BufferedImage img = null;
try{
img = ImageIO.read(originalImage);
for(int i = 0; i < img.getHeight(); i++){
for(int j = 0; j < img.getWidth(); j++){
//get the rgb color of the image and store it
Color c = new Color(img.getRGB(i, j));
int r = c.getRed();
int g = c.getGreen();
int b = c.getBlue();
//if the pixel is white then leave it alone
if((r == 255) && (g == 255) && (b == 255)){
img.setRGB(i, j, c.getRGB());
continue;
}
//set the colored pixel to 100,100,100
r = 100;// red component 0...255
g = 100;// green component 0...255
b = 100;// blue component 0...255
int col = (r << 16) | (g << 8) | b;
img.setRGB(i, j, col);
}
}
File f = new File("C:\\Users\\Me\\Desktop\\2\\1.png");
try {
ImageIO.write(img, "PNG", f);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e){
e.printStackTrace();
}
}
}
I have no clue why it doesn't set the pixels to the expected rgb value. I eventually want to be able to basically increment the rgb color as I move down rows and columns in the x and y so what the final image will look like is it will start off dark in the top left corner and then have a fade out effect as you get from that side to the bottom right corner.
Okay, based on the comments:
If the BufferedImage has an IndexColorModel (palette based color model), using setRGB to set a pixel to an arbitrary RGB value will not work. Instead, the color will be looked up, and the pixel will get the color that is considered the closest match in the palette.
Formats like BMP, GIF and PNG may all use IndexColorModel when read using ImageIO.
To convert the image to "true color" (either DirectColorModel or ComponentColorModel in Java will do), you can use:
BufferedImage img; // your original palette image
int w = img.getWidth();
int h = img.getHeight();
BufferedImage trueColor = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g = trueColor.createGraphics();
try {
g.drawImage(img, 0, 0, null);
}
finally {
g.dispose();
}
img = trueColor;
After this, getRGB(x, y) should return what you specify, using setRGB(x, y, argb).