Passing JRAbstractSvgRenderer (JRRenderable) in fillReport - java

I'm passing a simple implementation of JRAbstractSvgRenderer (taken from the ireports pdf manual) as one of the parameters using JasperFillManager.fillReport.
public class CustomImageRenderer extends JRAbstractSvgRenderer {
#Override
public void render(Graphics2D g2d, Rectangle2D rect) throws JRException {
System.out.println("CustomImageRenderer.render");
// Save the Graphics2D affine transform
AffineTransform savedTrans = g2d.getTransform();
Font savedFont = g2d.getFont();
// Paint a nice background...
g2d.setPaint(new GradientPaint(0, 0, Color.ORANGE,
0, (int) rect.getHeight(), Color.PINK));
g2d.fillRect(0, 0, (int) rect.getWidth(), (int) rect.getHeight());
Font myfont = new Font("Arial Black", Font.PLAIN, 50);
g2d.setFont(myfont);
FontRenderContext frc = g2d.getFontRenderContext();
String text = new String("JasperReports!!!");
TextLayout textLayout = new TextLayout(text, myfont, frc);
Shape outline = textLayout.getOutline(null);
Rectangle r = outline.getBounds();
// Translate the graphic to center the text
g2d.translate(
(rect.getWidth() / 2) - (r.width / 2),
rect.getHeight() / 2 + (r.height / 2));
g2d.setColor(Color.BLACK);
g2d.draw(outline);
// Restore the Graphics2D affine transform
g2d.setFont(savedFont);
g2d.setTransform(savedTrans);
}
}
...
Map parameters = new HashMap();
parameters.put("IMAGEPARAM", new CustomImageRenderer());
...
JasperPrint jasperPrint = JasperFillManager.fillReport(path, parameters, conn);
I have linked an Image component in my report to this parameter but the image does not display. What am I missing here?
What I'd like to accomplish is to eventually pass an already created Java2D image to my report but I don't want pass it as a raster image.

I don't know JasperReports, but you can create an off-screen java.awt.Image easily:
private Image getImage(int h, int w) {
BufferedImage bi = new BufferedImage(h, w, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = bi.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
// your drawing code
g2d.dispose();
return bi;
}
As a handy way to preview a rendering, you can create a JComponent that displays the image, e.g.:
JLabel label = new JLabel(new ImageIcon(getImage(h, w)));
Addendum: You might also try to determine if your renderer is being invoked at all or if it is somehow rendering nothing. If the latter, you might simplify your rendering code to some bare minimum such as setting the color and filling rect.

Related

How can i auto-size image when frame is maximised? [duplicate]

I have a PNG image and I want to resize it. How can I do that? Though I have gone through this I can't understand the snippet.
If you have an java.awt.Image, resizing it doesn't require any additional libraries. Just do:
Image newImage = yourImage.getScaledInstance(newWidth, newHeight, Image.SCALE_DEFAULT);
Obviously, replace newWidth and newHeight with the dimensions of the specified image.
Notice the last parameter: it tells the runtime the algorithm you want to use for resizing.
There are algorithms that produce a very precise result, however these take a large time to complete.
You can use any of the following algorithms:
Image.SCALE_DEFAULT: Use the default image-scaling algorithm.
Image.SCALE_FAST: Choose an image-scaling algorithm that gives higher priority to scaling speed than smoothness of the scaled image.
Image.SCALE_SMOOTH: Choose an image-scaling algorithm that gives higher priority to image smoothness than scaling speed.
Image.SCALE_AREA_AVERAGING: Use the Area Averaging image scaling algorithm.
Image.SCALE_REPLICATE: Use the image scaling algorithm embodied in the ReplicateScaleFilter class.
See the Javadoc for more info.
We're doing this to create thumbnails of images:
BufferedImage tThumbImage = new BufferedImage( tThumbWidth, tThumbHeight, BufferedImage.TYPE_INT_RGB );
Graphics2D tGraphics2D = tThumbImage.createGraphics(); //create a graphics object to paint to
tGraphics2D.setBackground( Color.WHITE );
tGraphics2D.setPaint( Color.WHITE );
tGraphics2D.fillRect( 0, 0, tThumbWidth, tThumbHeight );
tGraphics2D.setRenderingHint( RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR );
tGraphics2D.drawImage( tOriginalImage, 0, 0, tThumbWidth, tThumbHeight, null ); //draw the image scaled
ImageIO.write( tThumbImage, "JPG", tThumbnailTarget ); //write the image to a file
Try this:
ImageIcon icon = new ImageIcon(UrlToPngFile);
Image scaleImage = icon.getImage().getScaledInstance(28, 28,Image.SCALE_DEFAULT);
Resize image with high quality:
private static InputStream resizeImage(InputStream uploadedInputStream, String fileName, int width, int height) {
try {
BufferedImage image = ImageIO.read(uploadedInputStream);
Image originalImage= image.getScaledInstance(width, height, Image.SCALE_DEFAULT);
int type = ((image.getType() == 0) ? BufferedImage.TYPE_INT_ARGB : image.getType());
BufferedImage resizedImage = new BufferedImage(width, height, type);
Graphics2D g2d = resizedImage.createGraphics();
g2d.drawImage(originalImage, 0, 0, width, height, null);
g2d.dispose();
g2d.setComposite(AlphaComposite.Src);
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(resizedImage, fileName.split("\\.")[1], byteArrayOutputStream);
return new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
} catch (IOException e) {
// Something is going wrong while resizing image
return uploadedInputStream;
}
}
int newHeight = 150;
int newWidth = 150;
holder.iv_arrow.requestLayout();
holder.iv_arrow.getLayoutParams().height = newHeight;
holder.iv_arrow.getLayoutParams().width = newWidth;
holder.iv_arrow.setScaleType(ImageView.ScaleType.FIT_XY);
holder.iv_arrow.setImageResource(R.drawable.video_menu);
Simple way in Java
public void resize(String inputImagePath,
String outputImagePath, int scaledWidth, int scaledHeight)
throws IOException {
// reads input image
File inputFile = new File(inputImagePath);
BufferedImage inputImage = ImageIO.read(inputFile);
// creates output image
BufferedImage outputImage = new BufferedImage(scaledWidth,
scaledHeight, inputImage.getType());
// scales the input image to the output image
Graphics2D g2d = outputImage.createGraphics();
g2d.drawImage(inputImage, 0, 0, scaledWidth, scaledHeight, null);
g2d.dispose();
// extracts extension of output file
String formatName = outputImagePath.substring(outputImagePath
.lastIndexOf(".") + 1);
// writes to output file
ImageIO.write(outputImage, formatName, new File(outputImagePath));
}
Design jLabel first:
JLabel label1 = new JLabel("");
label1.setHorizontalAlignment(SwingConstants.CENTER);
label1.setBounds(628, 28, 169, 125);
frame1.getContentPane().add(label1); //frame1 = "Jframe name"
Then you can code below code:
ImageIcon imageIcon1 = new ImageIcon(new ImageIcon("add location url").getImage().getScaledInstance(100, 100, Image.SCALE_DEFAULT)); //100, 100 add your own size
label1.setIcon(imageIcon1);

getVisualBounds() return a dimension with all 0

The following code failed to read bounding rectangle of given korean text & font (NotoSansCJKKr-Regular.otf font), despite the fact that it works well on other Google fonts. What is the problem here anyway?
String text = "안녕하세요";
BufferedImage buf = new BufferedImage(1, 1 , BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = (Graphics2D)buf.getGraphics();
setRenderingHints(g2);
FontRenderContext frc = g2.getFontRenderContext();
GlyphVector glyph = g2.getFont().createGlyphVector(frc, text);
Rectangle rect = glyph.getVisualBounds().getBounds();
Result rect:
java.awt.Rectangle[x=0,y=0,width=0,height=0]

Why is my text-to-image method returning a fully-black image?

I'm trying to make a method that converts a given String (and Font) into a BufferedImage. However, every time I run it, it returns a fully black image. The exact size of the image seems to be correct, but all pixels are perfectly black.
Here's the code:
static final GraphicsEnvironment GE;
static
{
GE = GraphicsEnvironment.getLocalGraphicsEnvironment();
}
public static BufferedImage textToImage(String text, Font font)
{
if (font == null)
font = Font.getFont("Courier New");
FontRenderContext frc = new FontRenderContext(new AffineTransform(), false, false);
Rectangle2D bounds = font.getStringBounds(text, frc);
BufferedImage bi = new BufferedImage(
(int)(bounds.getWidth() + .5),
(int)(bounds.getHeight() + .5),
BufferedImage.TYPE_BYTE_BINARY
);
Graphics2D g = GE.createGraphics(bi);
g.setFont(font);
g.drawString(text, 0, 0);
return bi;
}
Here's "Hello World" in the default JOptionPane font displayed as a JOptionPane's icon:
The simple solution would be to change the color...
g.setColor(Color.WHITE);
g.fillRect(0, 0, bi.getWidth(), bi.getHeight());
g.setColor(Color.BLACK);
g.setFont(font);
g.drawString(text, 0, 0);
g.dispose();
Text, generally, isn't rendered from the y position down, it draw's up AND down from the y position, so you'll need to use something like...
FontMetrics fm = g.getFontMetrics();
g.drawString(text, 0, fm.getAscent());
to get the text to appear correctly...
Also font = Font.getFont("Courier New"); isn't doing what you think it is, this won't return the font named "Courier New", but will instead attempt to load the font file called "Courier New".
Try using something like...
if (font == null) {
font = new Font("Courier New", Font.PLAIN, 12);
}
instead...
You might like to take a closer look at Working with Text APIs for more details

How can I generate text image same as the JLabel label?

I would like to generate text image same as the JLabel label without displaying JLabel.
I tried same Font, same drawing method.
But generated image is not same as JLabel.
My sourcecode is below.
* 'super.paintComponent(g)' has been commented out for clarity that it is the same way. Output image is same.
* Below drawing by 'View.paint' method, but I'm tried 'SwingUtilities2.drawString' too. Two results are the same.
/* Label */
JLabel label = new JLabel(text) {
#Override
public void paintComponent(Graphics g) {
//super.paintComponent(g);
View v = BasicHTML.createHTMLView(this, getText());
v.paint(g, new Rectangle(0, 0, getWidth(), getFontMetrics(
getFont()).getAscent()));
}
};
label.setFont(new Font("Consolas", Font.PLAIN, 13));
/* Image */
FontMetrics fm = label.getFontMetrics(font);
BufferedImage image = new BufferedImage(fm.stringWidth(text),
fm.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = image.createGraphics();
g2d.setFont(label.getFont());
// Clear background.
g2d.setPaint(label.getBackground());
g2d.fillRect(0, 0, image.getWidth(), image.getHeight());
// Draw string.
g2d.setClip(new Rectangle(0, 0, image.getWidth(), image.getHeight()));
View v = BasicHTML.createHTMLView(label, text);
v.paint(g2d, new Rectangle(0, 0, image.getWidth(),
g2d.getFontMetrics().getAscent()));
// ... output image to file ...
Result image is following.
[JLabel]
[Generated image]
Generated image is slightly thin-faced, as compared to JLabel's capture.
How can I generate text image same as the JLabel label?
Thank you for your consideration.
I'm not sure, but you might need to create a compatible buffered image (compatible to the display)
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gs = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gs.getDefaultConfiguration();
// Create an image that does not support transparency
BufferedImage bimage = gc.createCompatibleImage(100, 100, Transparency.OPAQUE);
This will at least get you on a close with the graphics been used to render to the screen
You might also like to pay around with the rendering quality as well
Kleopatra did a post on a similar question awhile ago, you might to try and hunt it down
Why do you use BasicHTML.createView if you want to have the same as JLabel?
You could use the JLabel directly (if you only want the text and not the background, set opaque to false and the border to null)
or you can use g2d.drawString()

Is there a way to set a default color for transparency when using ColorConvertOp in Java2D?

I'm converting an image with transparency in it into a Colorspace that doesn't have transparency. I'd like to set a background color for the transparent areas. Right now when I convert it any area that is transparent turns to black in the final image. Is there a way to do that while I'm converting between ColorSpaces? Here is my code I use to convert between color spaces:
public BufferedImage convertColorspace( BufferedImage source, int newType) {
BufferedImage destination = new BufferedImage( source.getWidth(), source.getHeight(), newType);
ColorConvertOp colorConvertOp = new ColorConvertOp(null);
colorConvertOp.filter(source, destination);
return destination;
}
// here is how its used
BufferedImage converted = convertColorspace(combinedImage, BufferedImage.TYPE_3BYTE_BGR);
I'm converting from BufferedImage.TYPE_4BYTE_ARGB to BufferedImage.TYPE_3BYTE_BGR.
How about:
BufferedImage temp = new BufferedImage(source.getWidth(), source.getHeight(),
BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = temp.createGraphics();
g2.setColor(Color.green);
g2.fillRect(0, 0, source.getWidth(), source.getHeight());
g2.drawImage(0, 0, source, null);
g2.dispose();
Then call colorConvertOp.filter with temp instead of source.

Categories

Resources