I have an issue where I have an image with a fully black background that I have added text to. the program works well except that the background close, around the text, isn't fully black.
the program I'm trying to do takes a picture and areas where the pixels are bright add characters such as "#" and dark areas are filled with " "(space) or ".".
my current code is:
import java.awt.*;
import java.io.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
public static void main(String[] args) throws Exception {
BufferedImage image = ImageIO.read(new File("Person.jpg"));
Graphics g = image.getGraphics();
g.setFont(new Font("Times New Roman", Font.PLAIN,10));
Color backGround = new Color(0,0,0);
int bg = backGround.getRGB();
int pixelSize = 10;
for(int i = 0; i < image.getWidth()-pixelSize;i =pixelSize){
for(int j =0; j <image.getHeight()-pixelSize;j =pixelSize){
Color color = grayScale(image, i,j, pixelSize); /*grayScale() take the area...
of wanted pixel size and takes the average color and then grayscale it. */
for(int x = 0; x < pixelSize; x ){
for(int y = 0; y < pixelSize; y ){
image.setRGB(x i,y j, bg);
}
}
g.setColor(new Color(255,255,255));
g.drawString(acill(color), i, j); /* acill() maps the brightness of the pixel...
to a string of characters ex: string c = " .:!#" if the pixel i bright (255,255,255)
then the function returns "#". */
}
}
g.dispose();
ImageIO.write(image, "jpg", new File("Person1.jpg"));
}
}
CodePudding user response:
managed to solve it by changing the picture file from jpg to png. I do not know what causes this but at least it works. If anyone knows why I'd be happy to know.
CodePudding user response:
The noise you see in your image is fully expected, and is an artifact of lossy JPEG compression. You may get rid of some of it, by increasing the JPEG quality setting, at the expense of a larger file. But using lossy JPEG will always cause some such noise, and will never be able to exactly retain the information in your original image (thus "lossy"). JPEG is also created to compress "natural images" efficiently, and is not very good at compression "artificial" images like this.
As your image is black and white (bitonal) only, it is probably much better to use a lossless file format that natively supports bitonal images, like PNG, TIFF with "fax" compression, even BMP. For your image, these are likely to compress the data better than JPEG anyway. You could also use JBIG, which is a lossy format created for bitonal images, but only if you can accept the fact that it may not exactly retain your image.