I have a text document (.txt). I want to convert it to an image (.png or .jpg). For example, black text on white background. How can I do that programmatically?
I think the proper way for multi-line text is this:
String text = "This \nis \nmultiline";
final Rect bounds = new Rect();
TextPaint textPaint = new TextPaint() {
{
setColor(Color.WHITE);
setTextAlign(Paint.Align.LEFT);
setTextSize(20f);
setAntiAlias(true);
}
};
textPaint.getTextBounds(text, 0, text.length(), bounds);
StaticLayout mTextLayout = new StaticLayout(text, textPaint,
bounds.width(), Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
int maxWidth = -1;
for (int i = 0; i < mTextLayout.getLineCount(); i++) {
if (maxWidth < mTextLayout.getLineWidth(i)) {
maxWidth = (int) mTextLayout.getLineWidth(i);
}
}
final Bitmap bmp = Bitmap.createBitmap(maxWidth , mTextLayout.getHeight(),
Bitmap.Config.ARGB_8888);
bmp.eraseColor(Color.BLACK);// just adding black background
final Canvas canvas = new Canvas(bmp);
mTextLayout.draw(canvas);
FileOutputStream stream = new FileOutputStream(...); //create your FileOutputStream here
bmp.compress(CompressFormat.PNG, 85, stream);
bmp.recycle();
stream.close();
this (untested) code should get you on the right track.
void foo(final String text) throws IOException{
final Paint textPaint = new Paint() {
{
setColor(Color.WHITE);
setTextAlign(Paint.Align.LEFT);
setTextSize(20f);
setAntiAlias(true);
}
};
final Rect bounds = new Rect();
textPaint.getTextBounds(text, 0, text.length(), bounds);
final Bitmap bmp = Bitmap.createBitmap(bounds.width(), bounds.height(), Bitmap.Config.RGB_565); //use ARGB_8888 for better quality
final Canvas canvas = new Canvas(bmp);
canvas.drawText(text, 0, 20f, textPaint);
FileOutputStream stream = new FileOutputStream(...); //create your FileOutputStream here
bmp.compress(CompressFormat.PNG, 85, stream);
bmp.recycle();
stream.close();
}
This is what you need:
http://mvnrepository.com/artifact/org.apache.xmlgraphics/xmlgraphics-commons/1.3.1
I can provide you sample code if you want.
Edit: simple example:
package v13;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.OutputStream;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import org.apache.xmlgraphics.image.codec.png.PNGImageEncoder;
public class Deneme {
public static void main(String[]args){
JFrame jf = new JFrame();
jf.setVisible(true);
JPanel jp = new JPanel();
jf.add(jp);
JLabel jl = new JLabel("trial text");
jf.add(jl);
jf.setSize(300, 200);
JFileChooser jfc = new JFileChooser();
int temp = jfc.showSaveDialog(jfc);
if (temp == JFileChooser.APPROVE_OPTION) {
System.out.println(jfc.getSelectedFile());
Component myComponent = jf;
Dimension size = myComponent.getSize();
BufferedImage myImage = new BufferedImage(size.width,
size.height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = myImage.createGraphics();
myComponent.paint(g2);
try {
OutputStream out = new FileOutputStream(jfc
.getSelectedFile().getAbsolutePath()
+ ".png");
PNGImageEncoder encoder = new PNGImageEncoder(out, null);
encoder.encode(myImage);
out.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
}
Related
I'm using Barcode4J library to generate barcodes. I am returned a BufferedImage that I can display as an ImageIcon on a JLabel and save to a file but I can't for the life of me print it to a printer, the drawString and drawRect work as expected but the image is blank. I've posted some code below; I don't know how to make it a SSCCE of this but if anyone can point me in any direction I would be most grateful.
snippet:
import org.krysalis.barcode4j.impl.code128.Code128Bean;
import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;
import org.krysalis.barcode4j.tools.UnitConv;
public class BarcodeBean extends Code128Bean implements Printable{
BufferedImage _bImage;
public void createBarcode2Print(BarcodeBean bean, String barcodeValue) throws FileNotFoundException, IOException {
final int dpi = 150;
BufferedImage image;
BitmapCanvasProvider canvas = null;
if (barcodeValue == null) {
barcodeValue = "0123456789-000-0001";
}
bean.setModuleWidth(UnitConv.in2mm(2.0f / dpi));
bean.doQuietZone(false);
try {
canvas = new BitmapCanvasProvider(
dpi, BufferedImage.TYPE_BYTE_BINARY, false, 0);
//Generate the barcode
bean.generateBarcode(canvas, barcodeValue);
image = canvas.getBufferedImage();
//Signal end of generation
// canvas.finish();
} finally {
canvas.finish();
}
printImage(image);
int stop = 0;
}
public void printImage(BufferedImage arg_image){
_bImage = arg_image;
createLabel();
}
private void createLabel() {
PrinterJob printJob = PrinterJob.getPrinterJob();
Book book = new Book();
PageFormat format = new PageFormat();
format.setOrientation(PageFormat.PORTRAIT);
java.awt.print.Paper paper = new java.awt.print.Paper();
paper.setSize(612.0, 792.0); //portrait
double hgt = paper.getHeight();
double wdth = paper.getWidth();
paper.setImageableArea(0, 0, wdth, hgt);
format.setPaper(paper);
book.append(this, format);
printJob.setPageable(book);
if (printJob.printDialog()) {
try {
printJob.print();
} catch (PrinterException ex) {
ex.printStackTrace();
}
}
}
#Override
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
Graphics2D graphics2d = (Graphics2D)graphics;
graphics2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
graphics.setColor(Color.black);
graphics2d.setColor(Color.black);
int imageWidth = _bImage.getWidth(null); // 378
int imageHeight = _bImage.getHeight(null); // 110
int imageableWidth = (int)pageFormat.getImageableWidth(); // 612
int imageableHeight = (int)pageFormat.getImageableHeight(); // 792
graphics2d.drawString("Print barcode between this and...", 10, 30);
graphics2d.drawRect(10, 40, imageWidth, imageHeight);
graphics2d.drawImage(_bImage, 10, 60, imageWidth, imageHeight, null);
graphics2d.drawString("This.............................", 10, 180);
graphics2d.dispose();
return Printable.PAGE_EXISTS;
}
}
I can't say I know why, it's possible that the Barcode4J is using their own implementation of BufferedImage or something, but, if I make a copy of the BufferedImage returned from Barcode4J, I can make it work.
What I mean by that is, if I create a new instance of BufferedImage and draw the instance from Barcode4J onto it and use it, I can make it work...
canvas = new BitmapCanvasProvider(
dpi, BufferedImage.TYPE_BYTE_BINARY, false, 0);
bean.generateBarcode(canvas, barcodeValue);
BufferedImage bardcode = canvas.getBufferedImage();
image = new BufferedImage(bardcode.getWidth(), bardcode.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = image.createGraphics();
g2d.drawImage(bardcode, 0, 0, null);
g2d.dispose();
graphics2d.dispose(); ← That might be the problem. Never dispose of a Graphics unless you created it.
👆 is really good advice! Unfortunately, in this case it didn't help, but you should listen to it anyway!
Also, this return Printable.PAGE_EXISTS;, could have you running around in circles. You need to tell the caller when there are no more pages to be printed.
Runnable example...
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import org.krysalis.barcode4j.impl.code128.Code128Bean;
import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;
import org.krysalis.barcode4j.tools.UnitConv;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private BufferedImage barcodeImage;
public TestPane() throws IOException {
setLayout(new GridBagLayout());
barcodeImage = createBarcode2Print(new Code128Bean(), "0123456789-000-0001");
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(new JLabel(new ImageIcon(barcodeImage)), gbc);
JButton print = new JButton("Print");
add(print, gbc);
print.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
printIt();
}
});
}
protected void printIt() {
PrinterJob pj = PrinterJob.getPrinterJob();
if (pj.printDialog()) {
PageFormat pf = pj.defaultPage();
Paper paper = pf.getPaper();
pf.setOrientation(PageFormat.PORTRAIT);
pf.setPaper(paper);
PageFormat validatePage = pj.validatePage(pf);
// System.out.println("Valid- " + dump(validatePage));
pj.setPrintable(new BarCodePrintable(barcodeImage), validatePage);
try {
pj.print();
} catch (PrinterException ex) {
ex.printStackTrace();
}
}
}
}
public class BarCodePrintable implements Printable {
private BufferedImage barcodeImage;
public BarCodePrintable(BufferedImage barcodeImage) {
this.barcodeImage = barcodeImage;
}
#Override
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
Graphics2D graphics2d = (Graphics2D) graphics;
graphics2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
graphics.setColor(Color.black);
graphics2d.setColor(Color.black);
int imageWidth = barcodeImage.getWidth(); // 378
int imageHeight = barcodeImage.getHeight(); // 110
int imageableWidth = (int) pageFormat.getImageableWidth(); // 612
int imageableHeight = (int) pageFormat.getImageableHeight(); // 792
graphics2d.drawString("Print barcode between this and...", 10, 30);
graphics2d.drawRect(10, 40, imageWidth, imageHeight);
graphics2d.drawImage(barcodeImage, 10, 60, null);
graphics2d.drawString("This.............................", 10, 180);
//graphics2d.dispose();
return pageIndex == 0 ? Printable.PAGE_EXISTS : Printable.NO_SUCH_PAGE;
}
}
public BufferedImage createBarcode2Print(Code128Bean bean, String barcodeValue) throws FileNotFoundException, IOException {
final int dpi = 300;
BufferedImage image = null;
BitmapCanvasProvider canvas = null;
if (barcodeValue == null) {
barcodeValue = "0123456789-000-0001";
}
bean.setModuleWidth(UnitConv.in2mm(2.0f / dpi));
bean.doQuietZone(false);
try {
canvas = new BitmapCanvasProvider(
dpi, BufferedImage.TYPE_BYTE_BINARY, false, 0);
bean.generateBarcode(canvas, barcodeValue);
BufferedImage bardcode = canvas.getBufferedImage();
image = new BufferedImage(bardcode.getWidth(), bardcode.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = image.createGraphics();
g2d.drawImage(bardcode, 0, 0, null);
g2d.dispose();
} finally {
canvas.finish();
}
return image;
}
}
I am very new to Java. I need to add date as bottom-right corner text to captured image by my camera and save it. Like this:
Try this
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
public class WatermarkImage {
public static void main(String[] args) {
SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date now = new Date();
File origFile = new File("E:/watermark/test.jpg");
ImageIcon icon = new ImageIcon(origFile.getPath());
// create BufferedImage object of same width and height as of original image
BufferedImage bufferedImage = new BufferedImage(icon.getIconWidth(),
icon.getIconHeight(), BufferedImage.TYPE_INT_RGB);
// create graphics object and add original image to it
Graphics graphics = bufferedImage.getGraphics();
graphics.drawImage(icon.getImage(), 0, 0, null);
// set font for the watermark text
graphics.setFont(new Font("Arial", Font.BOLD, 20));
String watermark = sdfDate.format(now);
// add the watermark text
graphics.drawString(watermark, (icon.getIconWidth()*80)/100, (icon.getIconHeight()*90)/100);
graphics.dispose();
File newFile = new File("E:/watermark/WatermarkedImage.jpg");
try {
ImageIO.write(bufferedImage, "jpg", newFile);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(newFile.getPath() + " created successfully!");
}
}
Try this code.
// get today day. and put into ListView which is situated on bottom-right corner //in xml file.
final Calendar cal = Calendar.getInstance();
year = cal.get(Calendar.YEAR);
month = cal.get(Calendar.MONTH)+1;
day = cal.get(Calendar.DAY_OF_MONTH);
TextView out=(TextView)findViewById(R.id.yourtextview);
out.setText(day+"."+month+"."+year);
Try this code. It's saved lot of effort for me
String d = "18-11-2019";
BufferedImage bi = ImageIO.read(sourceFile);
Graphics2D graphics = bi.createGraphics();
Font font = new Font("ARIAL", Font.PLAIN, 50);
graphics.setFont(font);
graphics.drawString(d, 50, 50);
bi.flush();
ImageIO.write(bi, "jpg", targetFile);
for bottom right corner u can do somthinge like this
private Bitmap addWaterMark(Bitmap src) {
int w = src.getWidth();
int h = src.getHeight();
Bitmap result = Bitmap.createBitmap(w, h, src.getConfig());
Canvas canvas = new Canvas(result);
canvas.drawBitmap(src, 0, 0, null);
Bitmap waterMark = BitmapFactory.decodeResource(getResources(), R.drawable.watermark3x);
int ww = w-waterMark.getWidth();
int hh = h-waterMark.getHeight();
canvas.drawBitmap(waterMark, ww, hh, null);
return result;
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I need a java function that takes Image and Image Size (in Kb) as input and return output an image .
can anyone tell me the relationship between the Dimensions and Size (in Kb ) of Image .
Thanks in Advance !
Keep adjusting the compression in this example until the image size in bytes is below the limit.
Screen shot
Typical outputs
Fractional Metrics: true
Nonantialiased text mode
PNG size: 7390 bytes
JPG size: 7036 bytes quality: 35
Fractional Metrics: true
Antialiased text mode
PNG size: 8741 bytes
JPG size: 8663 bytes quality: 55
Fractional Metrics: false
Antialiased text mode
PNG size: 8720 bytes
JPG size: 8717 bytes quality: 55
Source
import java.awt.image.BufferedImage;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.imageio.*;
import java.io.*;
import javax.imageio.stream.ImageOutputStream;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import java.util.Locale;
class ImageCompressionDemo {
private BufferedImage originalImage;
private BufferedImage textImage;
private JPanel gui;
private JCheckBox antialiasing;
private JCheckBox rendering;
private JCheckBox fractionalMetrics;
private JCheckBox strokeControl;
private JCheckBox colorRendering;
private JCheckBox dithering;
private JComboBox textAntialiasing;
private JComboBox textLcdContrast;
private JLabel jpegLabel;
private JLabel pngLabel;
private JTextArea output;
private JSlider quality;
private int pngSize;
private int jpgSize;
final static Object[] VALUES_TEXT_ANTIALIASING = {
RenderingHints.VALUE_TEXT_ANTIALIAS_OFF,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON,
RenderingHints.VALUE_TEXT_ANTIALIAS_GASP,
RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HBGR,
RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB,
RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_VBGR,
RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_VRGB
};
final static Object[] VALUES_TEXT_LCD_CONTRAST = {
new Integer(100),
new Integer(150),
new Integer(200),
new Integer(250)
};
ImageCompressionDemo() {
int width = 280;
int height = 100;
gui = new JPanel(new BorderLayout(3,4));
quality = new JSlider(JSlider.VERTICAL, 0, 100, 75);
quality.setSnapToTicks(true);
quality.setPaintTicks(true);
quality.setPaintLabels(true);
quality.setMajorTickSpacing(10);
quality.setMinorTickSpacing(5);
quality.addChangeListener( new ChangeListener(){
public void stateChanged(ChangeEvent ce) {
updateImages();
}
} );
gui.add(quality, BorderLayout.WEST);
originalImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
textImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
JPanel controls = new JPanel(new GridLayout(0,1,0,0));
antialiasing = new JCheckBox("Anti-aliasing", false);
rendering = new JCheckBox("Rendering - Quality", true);
fractionalMetrics = new JCheckBox("Fractional Metrics", true);
strokeControl = new JCheckBox("Stroke Control - Pure", false);
colorRendering = new JCheckBox("Color Rendering - Quality", true);
dithering = new JCheckBox("Dithering", false);
controls.add(antialiasing);
controls.add(fractionalMetrics);
textLcdContrast = new JComboBox(VALUES_TEXT_LCD_CONTRAST);
JPanel lcdContrastPanel = new JPanel(new FlowLayout(FlowLayout.LEADING));
lcdContrastPanel.add(textLcdContrast);
lcdContrastPanel.add(new JLabel("Text LCD Contrast"));
controls.add(lcdContrastPanel);
textAntialiasing = new JComboBox(VALUES_TEXT_ANTIALIASING);
controls.add(textAntialiasing);
controls.add(dithering);
controls.add(rendering);
controls.add(colorRendering);
controls.add(strokeControl);
ItemListener itemListener = new ItemListener(){
public void itemStateChanged(ItemEvent e) {
updateImages();
}
};
antialiasing.addItemListener(itemListener);
rendering.addItemListener(itemListener);
fractionalMetrics.addItemListener(itemListener);
strokeControl.addItemListener(itemListener);
colorRendering.addItemListener(itemListener);
dithering.addItemListener(itemListener);
textAntialiasing.addItemListener(itemListener);
textLcdContrast.addItemListener(itemListener);
Graphics2D g2d = originalImage.createGraphics();
GradientPaint gp = new GradientPaint(
0f, 0f, Color.red,
(float)width, (float)height, Color.orange);
g2d.setPaint(gp);
g2d.fillRect(0,0, width, height);
g2d.setColor(Color.blue);
for (int ii=0; ii<width; ii+=10) {
g2d.drawLine(ii, 0, ii, height);
}
g2d.setColor(Color.green);
for (int jj=0; jj<height; jj+=10) {
g2d.drawLine(0, jj, width, jj);
}
gui.add(controls, BorderLayout.EAST);
JPanel images = new JPanel(new GridLayout(0,1,2,2));
images.add(new JLabel(new ImageIcon(textImage)));
try {
pngLabel = new JLabel(new ImageIcon(getPngCompressedImage(textImage)));
images.add(pngLabel);
jpegLabel = new JLabel(new ImageIcon(getJpegCompressedImage(textImage)));
images.add(jpegLabel);
} catch(IOException ioe) {
}
gui.add(images, BorderLayout.CENTER);
output = new JTextArea(4,40);
output.setEditable(false);
gui.add(new JScrollPane(output), BorderLayout.SOUTH);
updateImages();
JOptionPane.showMessageDialog(null, gui);
}
private Image getPngCompressedImage(BufferedImage image) throws IOException {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
ImageIO.write( image, "png", outStream );
pngSize = outStream.toByteArray().length;
BufferedImage compressedImage =
ImageIO.read(new ByteArrayInputStream(outStream.toByteArray()));
return compressedImage;
}
private Image getJpegCompressedImage(BufferedImage image) throws IOException {
float qualityFloat = (float)quality.getValue()/100f;
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
ImageWriter imgWriter = ImageIO.getImageWritersByFormatName( "jpg" ).next();
ImageOutputStream ioStream = ImageIO.createImageOutputStream( outStream );
imgWriter.setOutput( ioStream );
JPEGImageWriteParam jpegParams = new JPEGImageWriteParam( Locale.getDefault() );
jpegParams.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
jpegParams.setCompressionQuality( qualityFloat );
imgWriter.write( null, new IIOImage( image, null, null ), jpegParams );
ioStream.flush();
ioStream.close();
imgWriter.dispose();
jpgSize = outStream.toByteArray().length;
BufferedImage compressedImage = ImageIO.read(new ByteArrayInputStream(outStream.toByteArray()));
return compressedImage;
}
private void updateText() {
StringBuilder builder = new StringBuilder();
builder.append("Fractional Metrics: \t");
builder.append( fractionalMetrics.isSelected() );
builder.append("\n");
builder.append( textAntialiasing.getSelectedItem() );
builder.append("\nPNG size: \t");
builder.append(pngSize);
builder.append(" bytes\n");
builder.append("JPG size: \t");
builder.append(jpgSize);
builder.append(" bytes \tquality: ");
builder.append(quality.getValue());
output.setText(builder.toString());
}
private void updateImages() {
int width = originalImage.getWidth();
int height = originalImage.getHeight();
Graphics2D g2dText = textImage.createGraphics();
if (antialiasing.isSelected()) {
g2dText.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
} else {
g2dText.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_OFF);
}
if (rendering.isSelected()) {
g2dText.setRenderingHint(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
} else {
g2dText.setRenderingHint(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_SPEED);
}
if (fractionalMetrics.isSelected()) {
g2dText.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,
RenderingHints.VALUE_FRACTIONALMETRICS_ON);
} else {
g2dText.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,
RenderingHints.VALUE_FRACTIONALMETRICS_OFF);
}
if (strokeControl.isSelected()) {
g2dText.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL,
RenderingHints.VALUE_STROKE_NORMALIZE);
} else {
g2dText.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL,
RenderingHints.VALUE_STROKE_PURE);
}
if (dithering.isSelected()) {
g2dText.setRenderingHint(RenderingHints.KEY_DITHERING,
RenderingHints.VALUE_DITHER_ENABLE);
} else {
g2dText.setRenderingHint(RenderingHints.KEY_DITHERING,
RenderingHints.VALUE_DITHER_DISABLE);
}
if (colorRendering.isSelected()) {
g2dText.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING,
RenderingHints.VALUE_COLOR_RENDER_QUALITY);
} else {
g2dText.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING,
RenderingHints.VALUE_COLOR_RENDER_SPEED);
}
g2dText.setRenderingHint(RenderingHints.KEY_TEXT_LCD_CONTRAST,
textLcdContrast.getSelectedItem());
g2dText.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
textAntialiasing.getSelectedItem());
g2dText.drawImage(originalImage, 0,0, null);
g2dText.setColor(Color.black);
g2dText.drawString("The quick brown fox jumped over the lazy dog.", 10,50);
try {
jpegLabel.setIcon(new ImageIcon(getJpegCompressedImage(textImage)));
pngLabel.setIcon(new ImageIcon(getPngCompressedImage(textImage)));
} catch(IOException ioe) {
}
gui.repaint();
updateText();
}
public static void main(String[] args) {
SwingUtilities.invokeLater( new Runnable() {
public void run() {
ImageCompressionDemo iwt = new ImageCompressionDemo();
}
} );
}
}
I am trying to make image from BufferImage, but it's not working. here is my code ...
This code is not working, can anyone please help me ...
try {
BufferedImage bimage = (BufferedImage)(new ImageIcon("str")).getImage();
BufferedImage image = new BufferedImage(500, 500, bimage.TYPE_BYTE_GRAY);
File outputfile = new File("saved.png");
ImageIO.write(image, "png", outputfile);
Image image_1 = ImageIO.read(new File("saved.png"));
lp2_2.setIcon(new ImageIcon(image_1));
} catch (IOException e) {}
Maybe your way of converting IconImage to BufferedImageis not right.
So you can try the following snippet
BufferedImage bi = new BufferedImage(icon.getIconWidth(),icon.getIconHeight(), BufferedImage.TYPE_INT_RGB);
Graphics g = bi.createGraphics();
// paint the Icon to the BufferedImage.
icon.paintIcon(null, g, 0,0);
g.dispose();
After this you can use BufferdImage as you are already using.
Or you can look this question Java converting Image to BufferedImage
if you want to see how to convert Image to 'BifferedImage' because as given in this post you can't just cast Image to BufferedImage.
Although i would request you to add more information like what error or exception you are getting and may be if there is an exception add the stacktrace .
Hopefully this will work better, I have tried it many times.
public void writeImage(String output, String fileName, BufferedImage img) throws IOException {
File file = new File(output + "\\HE\\" + fileName + ".bmp");
ImageIO.write(img, "bmp", file);
}
=================================================================================
If you want to use this image in any JPanel then here is code for it, it is already working fine,
import java.awt.BorderLayout;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
public class ShowImage {
public ShowImage(final String filename) throws Exception {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame editorFrame = new JFrame("My Frame " +filename);
editorFrame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
BufferedImage image = null;
try {
image = ImageIO.read(new File(filename));
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
ImageIcon imageIcon = new ImageIcon(image);
JLabel jLabel = new JLabel();
jLabel.setIcon(imageIcon);
editorFrame.getContentPane().add(jLabel, BorderLayout.CENTER);
editorFrame.pack();
editorFrame.setLocationRelativeTo(null);
editorFrame.setVisible(true);
}
});
}
}
here is my new code and its working properly ... thank you all for your kind support ...
try{
BufferedImage cat = ImageIO.read(new File(str));
for (int w = 0; w < cat.getWidth(); w++) {
for (int h = 0; h < cat.getHeight(); h++) {
Color color = new Color(cat.getRGB(w, h));
//int averageColor = ((color.getRed() + color.getGreen() + color.getBlue()) / 3);
//int averageColor = int((color.getRed())*0.21 +(color.getGreen())*0.71+(color.getBlue())*0.07);
double r =color.getRed()*0.21;
double g =color.getGreen()*0.71;
double b =color.getBlue()*0.07;
int averageColor = (int)(r+g+b);
Color avg = new Color(averageColor, averageColor, averageColor);
cat.setRGB(w, h, avg.getRGB());
}
}
ImageIO.write(cat, "jpg", new File("image_greyscale.jpg"));
lp2_2.setIcon(new ImageIcon((new ImageIcon("image_greyscale.jpg")).getImage().getScaledInstance( 600, 600, java.awt.Image.SCALE_SMOOTH )));
}catch(IOException e){
e.printStackTrace();
System.exit(1);}
Everyone here missed the point. A BufferedImage is an Image.
Alright so I'm making a game, and I'm trying to modify the original hit marker image by adding text on it, and I'm using the following code:
import javax.swing.ImageIcon;
import javax.swing.Timer;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
public class HitMarker {
public static final Image rangeHitMarker = new ImageIcon(HitMarker.class.getResource("rangeHitMarker.png")).getImage();
public static final Image magicHitMarker = new ImageIcon(HitMarker.class.getResource("magicHitMarker.png")).getImage();
public static final Image monsterHitMarker = new ImageIcon(HitMarker.class.getResource("monsterHitMarker.png")).getImage();
public static final Font font = new Font("Tahoma", Font.PLAIN, 10);
public static final Color t = new Color(0,0,0,0);
public Image hitMarker;
public BufferedImage image;
public String hit;
public int attackStyle;
public boolean rangeAttack;
public int x;
public int y;
public Timer timer;
public boolean remove;
public HitMarker(int x, int y, int hit, int attackStyle){
this.hit = String.format("%d", hit);
this.remove = false;
this.x = x;
this.y = y;
this.attackStyle = attackStyle;
this.hitMarker = getImage();
BufferedImage bi = new BufferedImage(35, 20, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bi.createGraphics();
g.drawImage(hitMarker, 0, 0, null);
g.setFont(font);
g.setColor(Color.WHITE);
g.drawString(this.hit, 18, 13);
g.dispose();
image = bi;
timer = new Timer(800,
new ActionListener(){
public void actionPerformed(ActionEvent e){
remove = true;
timer.stop();
}
}
);
timer.setInitialDelay(800);
timer.start();
}
public HitMarker(int x, int y, int hit){
this.hit = String.format("%d", hit);
this.remove = false;
this.x = x;
this.y = y;
this.hitMarker = monsterHitMarker;
BufferedImage bi = new BufferedImage(35, 20, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bi.createGraphics();
g.drawImage(hitMarker, 0, 0, null);
g.setFont(font);
g.setColor(Color.WHITE);
g.drawString(this.hit, 18, 13);
g.dispose();
image = bi;
timer = new Timer(800,
new ActionListener(){
public void actionPerformed(ActionEvent e){
remove = true;
timer.stop();
}
}
);
timer.setInitialDelay(800);
timer.start();
}
public boolean isRangeAttack(){
return attackStyle == AttackStyleConstants.RANGE || attackStyle == AttackStyleConstants.RANGE_DEFENCE ? true : false;
}
public Image getImage(){
return isRangeAttack() ? rangeHitMarker : magicHitMarker;
}
}
Focusing particularly on either constructor:
And the error that I'm having is that when I create the BufferedImage and draw the image on the buffered image, it's creating a black background automatically and I don't know why. I've tried researching on this topic and some say to change something about the AlphaComposite and the g.clearRect() method, but neither of those seem to work. By the way, the image that I'm painting on the buffered image is 35x20 (which is the dimensions of the buffered image) and it has a transparent background. If anyone can tell me how to remove this black background, it would be very much appreciated, thank you.
Try BufferedImage.TYPE_INT_ARGB. This will make the regions transparent instead of black.
You might want to try and store the alpha channel as well,
BufferedImage bi = new BufferedImage(35, 20, BufferedImage.TYPE_INT_ARGB);
If you need a JPG with white background, you need to draw the image like this:
g.drawImage(hitMarker, 0, 0, Color.WHITE, null);
This way you avoid the black background when going from PNG to JPG.
Use png instead of jpeg. Png is much suitable for transparency operations.
Here is simple png export code snippet;
BufferedImage bImage = new BufferedImage(640, 480, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = (Graphics2D) bImage.getGraphics();
DrawingContext context = new DrawingContext(g2d);
plot.draw(context);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DrawableWriter wr = DrawableWriterFactory.getInstance().get("image/png");
wr.write(plot, baos, 640, 480);
baos.flush();
baos.close();
InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
BufferedImage bufferedImage = ImageIO.read(inputStream);
ImageIO.write(bufferedImage,"png",new File(outputFolder.getPath()+"/result.png"));