Printing the line separator character in an image [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Problems with newline in Graphics2D.drawString
String eol =System.lineSeparator();
String sampleText =epcURNText +eol+studentName+eol+DelayComments+eol+ArrivalMethodComments+eol;
System.out.println(sampleText);
Font font = new Font("Tahoma", Font.PLAIN, 11);
FontRenderContext frc = new FontRenderContext(null, true, true);
//get the height and width of the text
Rectangle2D bounds = font.getStringBounds(sampleText, frc);
int w = (int) bounds.getWidth();
int h = (int) bounds.getHeight();
//create a BufferedImage object
BufferedImage image = new BufferedImage(w, h,
BufferedImage.TYPE_INT_RGB);
//calling createGraphics() to get the Graphics2D
Graphics2D g = image.createGraphics();
//set color and other parameters
g.setColor(Color.WHITE);
g.fillRect(0, 0, w, h);
g.setColor(Color.BLACK);
g.setFont(font);
g.drawString(sampleText, (float) bounds.getX(),
(float) -bounds.getY());
//releasing resources
g.dispose();
// define the format of print document
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(image, "gif", os);
File f = new File("MyFile.jpg");
ImageIO.write(image, "JPEG", f);
Within the aforementioned code I am trying to print a string with newline characters within an image. However the newline character is omitted thus my text is presented within a single line? Does anybody have any idea on how to fix this?

Render the text in a JLabel with HTML formatting as shown the LabelRenderTest source in this answer.
It provides something better than line-breaks - the style for body width. Better in the sense that we do not need to manually calculate where to put line breaks for text (which also might be rendered in fonts that are not fixed width).

Related

JEditorPane and content width

I have some code where I take some text in html format, put it in a JEditorPane and create an image from it, as below:
String text = getMyText();
int height = getContentHeight(text);
int width = 850;
image = new BufferedImage(WIDTH, height, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = image.createGraphics();
graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
JEditorPane jep = new JEditorPane();
jep.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE);
jep.setContentType("text/html");
jep.setFont(new Font(myFont));
jep.setSize(width, height);
jep.setText(text);
jep.print(graphics);
graphics.dispose();
String fileName = "myFileName" + ".extension";
File outputfile = new File(myPath + "/" + fileName );
ImageIO.write(image, "png", outputfile);
This works wonderfully until the point I have some element in my html text with some fixed width (i.e. a div, or a table etc)
Since my original width is fixed at 850 pixels, if the width of that element is greater than that, what is happening is that the image looks like is being cut, meaning you cannot read certain text.
Is there a way so the text won't go over my fixed width? Or is it just a matter of making sure the width is within the limits beforehand?
Thanks for any help

Convert color image into black and white using java created from scratch

I want to convert my picture from colored to Black and white which seems to be created from scratch.
Here is the code which i tried as described on the different post:
BufferedImage bi = ImageIO.read(new File("/Users/***/Documents/Photograph.jpg"));
ColorConvertOp op =
new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null);
ImageIO.write(bi, "PNG", new File("/Users/bng/Documents/rendered2.png"));
op.filter(bi, bi);
But still my image is not converted to the Black and white. Additionally, this code is increasing the rendered2.png image size to 10 folds.
Also, it would be great if i could find some Java 8 way of doing this.
Any suggestions?
Here is the code which worked for me:
BufferedImage input = ImageIO.read(new File("/Users/bng/Documents/Photograph.jpg"));
// Create a black-and-white image of the same size.
BufferedImage im = new BufferedImage(input.getWidth(), input.getHeight(), BufferedImage.TYPE_BYTE_BINARY);
// Get the graphics context for the black-and-white image.
Graphics2D g2d = im.createGraphics();
// Render the input image on it.
g2d.drawImage(input, 0, 0, null);
// Store the resulting image using the PNG format.
ImageIO.write(im, "PNG", new File("/Users/bng/Documents/rendered.png"));
It was BufferedImage.TYPE_BYTE_BINARY which provided me the exact solution.
Lokking for the Java 8 Version for above code.
You have to find RGB of the existing colors of the image you want to change it.
Fyi, you want to change it as white RGB value is (255,255,255) and for black RGB value is (0,0,0)
Following method easily do the color change if you apply correct way of your requirement
private BufferedImage changeColor(BufferedImage image, int srcColor, int replaceColor)
{
BufferedImage destImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g = destImage.createGraphics();
g.drawImage(image, null, 0, 0);
g.dispose();
for (int width = 0; width < image.getWidth(); width++)
{
for (int height = 0; height < image.getHeight(); height++)
{
if (destImage.getRGB(width, height) == srcColor)
{
destImage.setRGB(width, height, replaceColor);
}
}
}
return destImage;
}
you have to use the ColorConvertOp in a proper way:
create Source image
apply filter
save dest
example:
BufferedImage src = ImageIO.read(new File("/Users/***/Documents/Photograph.jpg"));
ColorConvertOp op =
new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null);
BufferedImage dest = op.filter(src, null);
ImageIO.write(dest, "PNG", new File("/Users/bng/Documents/rendered2.png"));
src:
dest:

Java blurrying background with Graphics2D

I'm using Java to create an image with text. I set the color of the background and fill it up. Then I place the text using LineBreakMeasurer. The problem is (As you can see in the attached image) the image background around the text is blurry (if you zoom on). This is a problem for me. Is it possible to fix that?
final BufferedImage image = new BufferedImage(600, 400, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = image.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2d.setColor(new Color(255,0,0));
g2d.fillRect (0, 0, image.getWidth(), image.getHeight());
...
AttributedString attributedString = getAttributedString(text, fontSize, new Color(1.0f,1.0f,1.0f,0.9f));
AttributedCharacterIterator characterIterator = attributedString
.getIterator();
FontRenderContext fontRenderContext = g2d.getFontRenderContext();
LineBreakMeasurer measurer = new LineBreakMeasurer(characterIterator,
fontRenderContext);
while (measurer.getPosition() < characterIterator.getEndIndex()) {
TextLayout textLayout = measurer.nextLayout(width);
int currentX = x + (int)(width - textLayout.getVisibleAdvance()) / 2;
y += textLayout.getAscent();
textLayout.draw(g2d, currentX, y);
}
If you're referring to the artifacts around the letters, the problem isn't with your painting code. It's the result of saving the image as a JPEG. Save it using a non-lossy format, like PNG. You could also try reducing the compression of the JPEG, but saving as a PNG is probably easier.

Improve "drawString" methods text quality

I'm in the process of making a captcha in Java but I'm having trouble improving the text quality the "drawString" method generates on top of my image.
Example of the text quality:
You can actually see the horrible edges on the text.
Java code:
File file = new File("C:\\captcha.png");
File file2 = new File("C:\\captcha2.png");
File fontfile = new File("C:\\xerox.ttf");
BufferedImage bfimage = ImageIO.read(file);
Graphics2D g = bfimage.createGraphics();
Font myfont = Font.createFont(Font.PLAIN, fontfile);
myfont = myfont.deriveFont(50f);
g.setFont(myfont);
g.setColor(Color.black);
AffineTransform att = new AffineTransform();
g.translate(100, 50);
att.rotate(Math.toRadians(15), 100, 50);
g.setTransform(att);
g.drawString("12345", 100, 50);
RenderedImage rimg = bfimage;
ImageIO.write(rimg, "PNG", file2);
Example of same font used in php, but here the quality is A LOT better with smooth edges:
How do I improve the text quality generated by the "drawString" method in Java?
Graphics and Graphics2D provide a rendering hint framework that allows you to configure some parts of the rendering of a component. Use an antialiasing rendering hint:
g2d.setRenderingHint( RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT);
and you should get antialiased text on your captcha.
http://docs.oracle.com/javase/6/docs/api/java/awt/RenderingHints.html for reference

Java 1.6 Graphics2D: Rendering text into a box

I am looking for an easy way to render a String into a rectangular box within a JPG whereas line breaks should happen automatically for that text box.
Is this possible with Graphics2D ?
Rendering a string on a single line is easy, the following code snippet uses Antialiasing as well as a good JPG output compression quality:
BufferedImage img = ImageIO.read(new File(".../input.jpg"));
int width = img.getWidth();
int height = img.getHeight();
Color zgColor = new Color(0xAB,0x3C,0x2E);
Color grey = new Color(0xCC,0xCC,0xCC);
BufferedImage bufferedImage = new BufferedImage(width, height, img.getType());
Graphics2D g = bufferedImage.createGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// draw graphics
g.drawImage(img, 0, 0, null);
g.setColor(zgColor);
int y = 900;
int x = 50;
g.setFont(new Font("Arial", Font.BOLD, 80));
g.drawString("Demo Text", x, y);
y+=80;
g.setColor(Color.WHITE);
g.setFont(new Font("Arial", Font.BOLD, 60));
g.drawString("Some other text a bit below", x, y);
y+=400;
g.setFont(new Font("Arial", Font.BOLD, 30));
g.setColor(Color.WHITE);
g.drawString("AND THIS WOULD BE THE TEXT I'D LIKE TO FIT INTO A BOX WITH AUTOMATIC LINE BREAKS", x, y);
g.dispose();
// Save as high quality JPEG
File targetFile = new File(".......result.jpg");
//ImageIO.write(bufferedImage, "jpg", targetFile); // this would give bad quality!
Iterator iter = ImageIO.getImageWritersByFormatName("jpeg");
ImageWriter writer = (ImageWriter)iter.next();
ImageWriteParam iwp = writer.getDefaultWriteParam();
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwp.setCompressionQuality(1); // best quality
FileImageOutputStream output = new FileImageOutputStream(targetFile);
writer.setOutput(output);
IIOImage image = new IIOImage(bufferedImage, null, null);
writer.write(null, image, iwp);
writer.dispose();
System.out.println("Done.");
Check out LineBreakMeasurer. The API has some example code to get you started.
Or another approach is to create a JLabel with your image. Then you can add a JTextArea to the label and set the wrapping property on. Then the text will automatically wrap when you add the text area to the label. You will manually need to set the bounds of the text area within the label to control the placement of the text.

Categories