Using setSample with WritableRaster - java

I want to remove particular color, and when I set
wrres.setSample(x, y, 0, wrsrc.getSample(x, y, 0)) ;
I don't have error but when I set something else like
wrres.setSample(x, y, 1, wrsrc.getSample(x, y, 1)) ; then I've got
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Coordinate out of bounds!
at java.awt.image.MultiPixelPackedSampleModel.getSample(MultiPixelPackedSampleModel.java:359)
at java.awt.image.Raster.getSample(Raster.java:1648)
it gives me the same image (just copied)
BufferedImage imres = user_space(img,1);
int height = img.getHeight();
int width = img.getWidth();
BufferedImage imsrc = img; // The source image, RGBA
BufferedImage imres = user_space(img,1); // The resulting image, RGB or BGR
WritableRaster wrsrc = imsrc.getRaster() ;
WritableRaster wrres = imres.getRaster() ;
for (int y=0 ; y < img.getHeight() ; y++)
for (int x=0 ; x < img.getWidth() ; x++)
{
wrres.setSample(x, y, 0, wrsrc.getSample(x, y, 0)) ;
wrres.setSample(x, y, 1, wrsrc.getSample(x, y, 1)) ;
wrres.setSample(x, y, 2, wrsrc.getSample(x, y, 2)) ;
}
return
new BufferedImage(imsrc.getColorModel(),wrres,imsrc.getColorModel().isAlphaPremultiplied(), null);
}
How to use setSample to set different colors not only black and white(band equal to 0 ) '
I don't want to use getRGB from BufferedImage

Related

Java: problem when bitmap.setPixel() replaced by bitmap.setPixels()

I have the following code:
Bitmap bitmap = Bitmap.createBitmap(WIDTH, HEIGHT, Bitmap.Config.ARGB_4444);
for (int y = 0; y < HEIGHT; y++) {
for (int x = 0; x < WIDTH; x++) {
int index = y * WIDTH + x;
bitmap.setPixel(x, y, Color.argb(255, 0, mask[index],0)); // mask is an array of int between 0 and 255
}
}
It works properly: I get my bitmap but...this code is really extremely slow.
I tried to replace it with:
Bitmap bitmap = Bitmap.createBitmap(WIDTH, HEIGHT, Bitmap.Config.ARGB_4444);
bitmap.setPixels(mask, 0, WIDTH, 0, 0, WIDTH, HEIGHT);
but this is not working. I get a black image.
Anybody can help ?
Thanks !

Converting subimage to RGB-A

I am working on a 2D platform game and I have a sprite sheet which includes the sprites of tiles and blocks.
I noticed that there was a pink-ish background behind the transparent sprites so I thought that Java wasn't loading the sprites as PNG and I tried to re-draw the sprite on a new bufferedImage, pixel by pixel checking if the pixel was R=255, G=63, B=52 but unfortunately, the code wasn't able to detect that either and at this point I have no more options left to try.
I made sure that the "pink" color values are correct by using a color picker.
original spritesheet (transparent):
The class that loads the sprite(s) is:
public class SpriteSheet {
private BufferedImage image;
public SpriteSheet(BufferedImage image) {
this.image = image;
}
public BufferedImage grabImage(int col, int row, int width, int height) {
BufferedImage alpha = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
BufferedImage img = image.getSubimage(
(col * width) - width,
(row * height) - height,
width,
height);
int w = img.getWidth();
int h = img.getHeight();
for(int y = 0; y < h; y++) {
for(int x = 0; x < w; x++) {
int pixel = img.getRGB(x, y);
int red, green, blue;
red = (pixel >> 16) & 0xff;
green = (pixel >> 8) & 0xff;
blue = (pixel) & 0xff;
if(red == 255 && green == 63 && blue == 52)
alpha.setRGB(x, y, new Color(0, 0, 0, 0).getRGB());
else
alpha.setRGB(x, y, pixel);
}
}
return alpha;
}
}
the class that loads the sprite sheet is:
public class Texture {
SpriteSheet bs, ss;
private BufferedImage block_sheet = null;
public BufferedImage[] block = new BufferedImage[3];
public Texture() {
BufferedImageLoader loader = new BufferedImageLoader();
try {
block_sheet = loader.loadImage("/tiles.png");
} catch(Exception e) {
e.printStackTrace();
}
bs = new SpriteSheet(block_sheet);
getTextures();
}
private void getTextures() {
block[0] = bs.grabImage(1, 1, 32, 32);
block[1] = bs.grabImage(2, 1, 32, 32);
block[2] = bs.grabImage(4, 1, 32, 32);
}
}
How do I get rid of the pink-ish background and keep transparency?
I dont understand why you're using subImage.
try {
BufferedImage img = ImageIO.read(new File("D:/image.png"));
for (int i = 0; i < img.getWidth(); i++) {
for (int j = 0; j < img.getHeight(); j++) {
Color pixelcolor = new Color(img.getRGB(i, j));
int r = pixelcolor.getRed();
int g = pixelcolor.getGreen();
int b = pixelcolor.getBlue();
if (r == 255 && g == 63 && b == 52) {
int rgb = new Color(255, 255, 255).getRGB();
img.setRGB(i, j, rgb);
}
}
}
ImageIO.write(img, "png", new File("D:/transparent.png"));
} catch (Exception e) {
System.err.println(e.getMessage());
}
cough, It worked all along, I had forgotten to disable the test blocks which was representing the blocks. Realized this after some time.
So the transparency was working fine. I just saw the rectangle i was drawing behind it.

How to convert image to black & white image and remove shadow in andorid Using OpenCV

I have a code that turns a RGB bitmap into a bitmap of black and white colors, using this code:
public static Bitmap setDefaultValues(Bitmap bmp) {
Mat srcMat = new Mat();
org.opencv.android.Utils.bitmapToMat(bmp, srcMat, true);
final Bitmap bitmap = Bitmap.createBitmap(srcMat.clone().width(), srcMat.clone().height(), Bitmap.Config.ARGB_8888);
Imgproc.cvtColor(srcMat, srcMat, Imgproc.COLOR_BGR2GRAY, 0);
Mat srcMat1 = srcMat;
Imgproc.GaussianBlur(srcMat1, srcMat1, new Size(3, 3), 0);
//Mat srcMat1 = new Mat(srcMat.rows(), srcMat.cols(), CV_8UC1);
//int kernalsize = 3;
//Imgproc.bilateralFilter(srcMat, srcMat1, kernalsize, kernalsize * 2, kernalsize / 2);
srcMat1.convertTo(srcMat1, 0, 1.9, -120);
srcMat1.convertTo(srcMat1, CvType.CV_8U, 1.9, -120);
Imgproc.cvtColor(srcMat1, srcMat1, Imgproc.COLOR_GRAY2RGBA, 4);
org.opencv.android.Utils.matToBitmap(srcMat, bitmap, true);
return bitmap;
}
I have implement this code for convert RGB image into black and white.
this is return me as right, but my question is here i cant remove shadow from image.
also i have compare other application this is convert perfectly, i don't understand where i am wrong.
this is original Image :
this is my application output
this is other application output
So please help me how can i achieve my goal.
Please use following code for convert your color image to black and white.
public static Bitmap createContrast(Bitmap src, double value) {
// 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;
// get contrast value
double contrast = Math.pow((100 + value) / 100, 2);
// 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);
A = Color.alpha(pixel);
// apply filter contrast for every channel R, G, B
R = Color.red(pixel);
R = (int)(((((R / 255.0) - 0.5) * contrast) + 0.5) * 255.0);
if(R < 0) { R = 0; }
else if(R > 255) { R = 255; }
G = Color.red(pixel);
G = (int)(((((G / 255.0) - 0.5) * contrast) + 0.5) * 255.0);
if(G < 0) { G = 0; }
else if(G > 255) { G = 255; }
B = Color.red(pixel);
B = (int)(((((B / 255.0) - 0.5) * contrast) + 0.5) * 255.0);
if(B < 0) { B = 0; }
else if(B > 255) { B = 255; }
// set new pixel color to output bitmap
bmOut.setPixel(x, y, Color.argb(A, R, G, B));
}
}
return bmOut;}
Please try this if you will get the solution
public static Bitmap test(Bitmap src){
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;
for (int x = 0; x < width; ++x) {
for (int y = 0; y < height; ++y) {
// get pixel color
pixel = src.getPixel(x, y);
A = Color.alpha(pixel);
R = Color.red(pixel);
G = Color.green(pixel);
B = Color.blue(pixel);
int gray = (int) (0.2989 * R + 0.5870 * G + 0.1140 * B);
// use 128 as threshold, above -> white, below -> black
if (gray > 128) {
gray = 255;
}
else{
gray = 0;
}
// set new pixel color to output bitmap
bmOut.setPixel(x, y, Color.argb(A, gray, gray, gray));
}
}
return bmOut;
}
Please see the answer on this thread. He has explained and provide a good result in output.
#Threshold image using opencv (Java)

How to get pixel color from Graphics g [duplicate]

This question already has answers here:
How to color a pixel?
(4 answers)
Closed 3 years ago.
On my study I have graphics lessons. We have Bresenham for line drawing and Circle drawing. On next lesson I will be learning flood fill. For flood fill I need to get pixel color to check whether I need to fill or not to fill.
This is my code now from all lessons.
package lab1;
import javax.swing.*;
import java.awt.*;
import java.util.Random;
public class Lab1 extends JPanel{
private Random random = new Random();
private boolean isRed;
private String s = "";
private int Fill(int x,int y,Graphics g)
{
if ((x < 0) || (y < 0) || (x >= 600) || (y >= 600)) return 0;
return 0;
}
private void drawCircle(int centerX,int centerY,int radius, Graphics g) {
Graphics2D g2d = (Graphics2D) g;
int d = (5 - radius * 4)/4;
int x = 0;
int y = radius;
Color circleColor = Color.white;
do {
g2d.drawRect(centerX + x, centerY + y, 1,1);
g2d.drawRect(centerX + x, centerY - y, 1,1);
g2d.drawRect(centerX - x, centerY + y, 1,1);
g2d.drawRect(centerX - x, centerY - y, 1,1);
g2d.drawRect(centerX + y, centerY + x, 1,1);
g2d.drawRect(centerX + y, centerY - x, 1,1);
g2d.drawRect(centerX - y, centerY + x,1,1);
g2d.drawRect(centerX - y, centerY - x, 1,1);
if (d < 0) {
d += 2 * x + 1;
} else {
d += 2 * (x - y) + 1;
y--;
}
x++;
} while (x <= y);
}
public void line(int x,int y,int x2, int y2, Graphics g) {
Graphics2D g2d = (Graphics2D) g;
//super.paintComponent(g);
int w = x2 - x ;
int h = y2 - y ;
int dx1 = 0, dy1 = 0, dx2 = 0, dy2 = 0 ;
if (w<0) dx1 = -1 ; else if (w>0) dx1 = 1 ;
if (h<0) dy1 = -1 ; else if (h>0) dy1 = 1 ;
if (w<0) dx2 = -1 ; else if (w>0) dx2 = 1 ;
int longest = Math.abs(w) ;
int shortest = Math.abs(h) ;
if (!(longest>shortest)) {
longest = Math.abs(h) ;
shortest = Math.abs(w) ;
if (h<0) dy2 = -1 ; else if (h>0) dy2 = 1 ;
dx2 = 0 ;
}
int numerator = longest >> 1 ;
for (int i=0;i<=longest;i++) {
g2d.drawRect(x, y, 1, 1);
numerator += shortest ;
if (!(numerator<longest)) {
numerator -= longest ;
x += dx1 ;
y += dy1 ;
} else {
x += dx2 ;
y += dy2 ;
}
}
}
public Lab1() {
}
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
drawCircle(100,500,50,g);
drawCircle(500,500,50,g);
g.setColor(Color.red);
line(50,450,550,450,g);
line(50,450,50,350,g);
line(50,350,150,350,g);
line(150,350,325,175,g);
line(325,175,400,175,g);
line(400,175,400,325,g);
line(400,325,550,325,g);
line(550,325,550,450,g);
}
//main method: create an instance of TestPanel and output it on a JFrame
public static void main(String[] args) {
JFrame f = new JFrame();
f.setSize(600, 600);
f.setTitle("Sometimes Red, Sometimes Blue");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setContentPane(new Lab1());
f.setVisible(true);
}
}
How to get pixel color from x and y ?
You can not read pixels from a Graphics object. Graphics is an abstraction for drawing, there might not be pixels (think of printing, plotting etc.).
You can create a java.awt.BufferedImage and use its createGraphics() method to get a Graphics to render into, while being able to read pixels using BufferedImage's getRGB() method to access pixels.
I would suggest to fill into a BufferedImage. There you can get the RGB value of each pixel with BufferedImage.getRGB

How to flip an image horizontally

HiI was wondering how to flip and image horizontally, for a practce task I was given a code that reads an image, inverting it to an image indicating it's brightness from 0-5, I had to flip an image.
This is my code of my reading an image and drawing it
public int[][] readImage(String url) throws IOException
{
// fetch the image
BufferedImage img = ImageIO.read(new URL(url));
// create the array to match the dimensions of the image
int width = img.getWidth();
int height = img.getHeight();
int[][] imageArray = new int[width][height];
// convert the pixels of the image into brightness values
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
// get the pixel at (x,y)
int rgb = img.getRGB(x,y);
Color c = new Color(rgb);
int red = c.getRed();
int green = c.getGreen();
int blue = c.getBlue();
// convert to greyscale
float[] hsb = Color.RGBtoHSB(red, green, blue, null);
int brightness = (int)Math.round(hsb[2] * (PIXEL_CHARS.length - 1));
imageArray[x][y] = brightness;
}
}
return imageArray;
}
public void draw() throws IOException
{
int[][] array = readImage("http://sfpl.org/images/graphics/chicklets/google-small.png");
for(int i=0; i<array.length; i++)
{
for(int pic=0; pic<array[i].length; pic++)
{
if(array[pic][i] == 0)
{
System.out.print("X");
}
else if(array[pic][i] == 1)
{
System.out.print("8");
}
else if(array[pic][i] == 2)
{
System.out.print("0");
}
else if(array[pic][i] == 3)
{
System.out.print(":");
}
else if(array[pic][i] == 4)
{
System.out.print(".");
}
else if (array[pic][i] == 5)
{
System.out.print(" ");
}
else
{
System.out.print("error");
break;
}
}
System.out.println();
}
}
and this is the code I tried to create to horizontally flip it,
void mirrorUpDown()
{
int[][] array = readImage("http://sfpl.org/images/graphics/chicklets/google-small.png");
int i = 0;
for (int x = 0; x < array.length; x++)
{
for (int y = 0; y < array[i].length; y++)
{{
int temp = array[x][y];
array[x][y]= array[-x][y];
array[array[i].length-x][y]=temp;
}
}
}
}
I get an error
unreported exception java.io.IException;
must be caught or declared to be thrown
I'd actually do it by this way...
BufferedImage flip(BufferedImage sprite){
BufferedImage img = new BufferedImage(sprite.getWidth(),sprite.getHeight(),BufferedImage.TYPE_INT_ARGB);
for(int xx = sprite.getWidth()-1;xx>0;xx--){
for(int yy = 0;yy < sprite.getHeight();yy++){
img.setRGB(sprite.getWidth()-xx, yy, sprite.getRGB(xx, yy));
}
}
return img;
}
Just a loop whose x starts at the end of the first image and places its rgba value on the flipped position of the second image. Clean, easy code :)
The function mirrorUpDown() , add a throws IOException there.
Also the function from which you are calling these methods, does that handle exception, does that code enclosed in a try catch block or the function is also set to throw IOException (one of either should be there)
How is your image supposed to know it should get it's data from imageArray ?
instead, you should access the raster of your image and modify the data in it.
void flip(BufferedImage image) {
WritableRaster raster = image.getRaster();
int h = raster.getHeight();
int w = raster.getWidth();
int x0 = raster.getMinX();
int y0 = raster.getMinY();
for (int x = x0; x < x0 + w; x++){
for (int y = y0; y < y0 + h / 2; y++){
int[] pix1 = new int[3];
pix1 = raster.getPixel(x, y, pix1);
int[] pix2 = new int[3];
pix2 = raster.getPixel(x, y0 + h - 1 - (y - y0), pix2);
raster.setPixel(x, y, pix2);
raster.setPixel(x, y0 + h - 1 - (y - y0), pix1);
}
}
return;
}
Sorry about posting this here over a year later but it should aid someone at a stage
try{
java.awt.image.BufferedImage bi = javax.imageio.ImageIO.read(getClass().getResource("Your image bro.jpg")) ;
int[] h = bi.getRGB(0, 0, bi.getWidth(), bi.getHeight(), null, 0, bi.getWidth());
int [] h1 = new int[h.length];
System.out.println(""+h.length);
for(int j = 0;500>j;j++){
for(int i = 500;i>0;i--){
h1[j*500+(500-i)] = h[(j*500)+(i-1)];
}
}
bi.setRGB(0, 0, bi.getWidth(), bi.getHeight(), h1, 0, bi.getWidth());
}
catch(Exception e){e.printStackTrace();}
Lets break the code down
java.awt.image.BufferedImage bi =javax.imageio.ImageIO.read(getClass().getResource("Your image bro.jpg"));
Tries to read the image and stores the read image into the BufferedImage variable bi
int[] h = bi.getRGB(0, 0, bi.getWidth(), bi.getHeight(), null, 0, bi.getWidth());
int [] h1 = new int[h.length];
instantiate two arrays, h is the original RGB Array and h1 will be the horizontally flipped RGB array.
for(int j = 0;500>j;j++){
for(int i = 500;i>0;i--){
h1[j*500+(500-i)] = h[(j*500)+(i-1)];
}
}
Lets look at something in particular more closely
h1[j*500+(500-i)] = h[(j*500)+(i-1)];
Images are scanned from position 0;0 to x.length;y.length
but it is scanned in a coninual array. Thus we use a psuedo-array to manipulate the flipping of the image. j*500 references the Y values and (500-i) references the x values.
bi.setRGB(0, 0, bi.getWidth(), bi.getHeight(), h1, 0, bi.getWidth());
Finally, the image gets stored back into the BufferedImage variable.
Note that the 500 constant is referencing your x resolution of the image. For example, 1920 x 1080 sized image uses a max value of 1920. The logic is yours to decide.

Categories