I have drawn an image in inkscape.I can see the option to export it as javafx script file i.e .fx. But as per my knowledge .fx is obsolete now in javafx 8.So it is not recommend to use it.I can use the svg images using the batik where I have to convert them to javafx image format then I can set it to imageview .I want this image to be scaled automatically when ever i moved my application to bigger resolution.Any help on this will be appreciated .
My custom Transcoder Code
import java.awt.image.BufferedImage;
import java.io.InputStream;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.image.Image;
import javafx.scene.image.WritableImage;
import org.apache.batik.transcoder.TranscoderException;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.ImageTranscoder;
import org.apache.batik.transcoder.image.PNGTranscoder;
class MyTranscoder extends ImageTranscoder {
private BufferedImage image = null;
private InputStream url;
MyTranscoder(InputStream url) {
this.url = url;
}
#Override
public BufferedImage createImage(int w, int h) {
image = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
return image;
}
#Override
public void writeImage(BufferedImage img, TranscoderOutput out) {
}
public BufferedImage getImage() {
return image;
}
public Image getJavafxCompatibleImage(int width, int height) {
this.addTranscodingHint(PNGTranscoder.KEY_WIDTH, (float) width);
this.addTranscodingHint(PNGTranscoder.KEY_HEIGHT, (float) height);
TranscoderInput input = new TranscoderInput(url);
try {
this.transcode(input, null);
} catch (TranscoderException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedImage bimage = this.getImage();
WritableImage wimage = SwingFXUtils.toFXImage(bimage, null);
return wimage;
}
}
Related
I'm trying to load and a bunch of Images into a program and repaint them 60times per second.My Problem is that I get a CPU usage of over 20% and the program isn't even finished.
This is the loop that load's the Image:
for(int i = 0;i < LevelCompiler.Objectlenght;i++) {
LevelCompiler.objects[i].drawObjects(g);
}
and this is the drawObjects methode:
g.drawRect(x, y, width, height);
g.drawImage(TextureSystem.textureSystem(TextureID), x, y, width, height, null);
The textureSystem methode that load's the imgae:
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
public class TextureSystem {
static String TexturePath;
static BufferedImage img;
public static BufferedImage textureSystem(int tid) {
TexturePath = "/textures/Objects/SObject+" + tid + ".jpg";
try {
img = ImageIO.read(ResourceLoader.load((TexturePath)));
} catch (IOException e) {
e.printStackTrace();
}
return img;
}
}
and this is the ResourceLoader from above
import java.io.InputStream;
public final class ResourceLoader {
public static InputStream load(String path) {
InputStream input = ResourceLoader.class.getResourceAsStream(path);
if (input == null) {
System.out.println("error");
}
return input;
}
}
I assume that the high CPU usage is because I'm loading the image again and again.Any suggetions how for another methode?
What is the shortest code one can write in java to break an image (say 200x1000) into 10 images of a tenth height but same width (200x 100)?
Mine is a pretty long code; the main part , I am just giving:
for (int i_=0;i_<10;i_++)
{
for(int k=i_*100;k<i_*100+h/10;k++)
{
for(int j_=0;j_<w;j_++)
{
int pixv=img.getRGB(j_,k);
r=(pixv>>16)&0xff;
g=(pixv>>8)&0xff;
b=(pixv)&0xff;
int rgb=new Color(r,g,b).getRGB();
img.setRGB(j_,k-i_*200,rgb);
}
}
// Here I am writing the img to a new .bmp file thus creating 10 seperate files
}
Here img is a BufferedImage
w,h the width and height of large image
you can get a sub image from BufferedImage using getSubimage(int x,int y,int w,int h). Try this:
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class NewClass9 {
public static void main(String[] args) throws IOException{
BufferedImage img = null;
img = ImageIO.read(new File("C:\\users\\uzochi\\desktop\\Penguins.jpg"));
for(int i = 0;i<10;i++){
BufferedImage sub = img.getSubimage(0, i*(img.getHeight()/10), img.getWidth(), img.getHeight()/10);
File f = new File("C:\\users\\uzochi\\desktop\\SubImage"+i+".png");
ImageIO.write(sub, "png", f);
}
}
}
I have been busy with trying to get the webcam to work within netbeans over the past few days.
The problem I am having is to get the coding to activate and take a picture using the webcam.
So far I have seen that I will have to use the OpenCV and some other JAR files.
Please could someone help me out by perfecting the coding I have below:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// coding for webcam and taking a picture
OpenCVFrameGrabber grabber = new OpenCVFrameGrabber(0);
try
{
//start of the webcam for taking the picture
grabber.start();
Image IM = this.takePicture();
//stops the webcam
grabber.stop();
}
catch (Exception e)
{
//displays error message if problem with webcam
JOptionPane.showMessageDialog(null, "Problem accessing or using the Webcam!");
}
}
What I need is for the picture to be displayed in a label on my interface after it has taken the picture.
The Open CV has been successfully installed and now just the coding needed to get the picture taken.
Any Help would be helpful.
Okay, your coding is a bit off, it does need some changes made to it. You are on the right track however.
I do have a sample code that may be able to help you out which works:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
// coding for webcam and taking a picture
OpenCVFrameGrabber grabber = new OpenCVFrameGrabber(0);
try
{
//start of the webcam for taking the picture
grabber.start();
//grabs teh image taken from the webcam
IplImage img = grabber.grab();
//checks if the webcam has taken the picture and if the picture if mot empty
if(img != null)
{
//determines where to save the picture
cvSaveImage("C:\\User1\\PrifilePicture\\"+lbl_StudnetLogin.getText()+".jpeg", img);
}
//stops the webcam
grabber.stop();
//used to resize teh picture taken in order to display picture to the user
Image imeResize = ImageIO.read(new File("C:\\SalVentri\\PrifilePicture\\"+lbl_StudnetLogin.getText()+".jpeg"));
//1st ---> width _______2sn ---> height
lbl_Profile.setIcon(new ImageIcon(imeResize.getScaledInstance(155, 100, 100)));
}
catch (Exception e)
{
//displays error message if problem with webcam
JOptionPane.showMessageDialog(null, "Problem accessing or using the Webcam!");
}
}
Hope this helps
I found that this works as well.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.awt.image.WritableRaster;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.opencv.core.*;
import org.opencv.highgui.Highgui;
import org.opencv.highgui.VideoCapture;
public class JPanelOpenCV extends JPanel{
BufferedImage image;
public static void main (String args[]) throws InterruptedException{
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
JPanelOpenCV t = new JPanelOpenCV();
VideoCapture camera = new VideoCapture(0);
Mat frame = new Mat();
camera.read(frame);
if(!camera.isOpened()){
System.out.println("Error");
}
else {
while(true){
if (camera.read(frame)){
BufferedImage image = t.MatToBufferedImage(frame);
t.window(image, "Original Image", 0, 0);
t.window(t.grayscale(image), "Processed Image", 40, 60);
//t.window(t.loadImage("ImageName"), "Image loaded", 0, 0);
break;
}
}
}
camera.release();
}
#Override
public void paint(Graphics g) {
g.drawImage(image, 0, 0, this);
}
public JPanelOpenCV() {
}
public JPanelOpenCV(BufferedImage img) {
image = img;
}
//Show image on window
public void window(BufferedImage img, String text, int x, int y) {
JFrame frame0 = new JFrame();
frame0.getContentPane().add(new JPanelOpenCV(img));
frame0.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame0.setTitle(text);
frame0.setSize(img.getWidth(), img.getHeight() + 30);
frame0.setLocation(x, y);
frame0.setVisible(true);
}
//Load an image
public BufferedImage loadImage(String file) {
BufferedImage img;
try {
File input = new File(file);
img = ImageIO.read(input);
return img;
} catch (Exception e) {
System.out.println("erro");
}
return null;
}
//Save an image
public void saveImage(BufferedImage img) {
try {
File outputfile = new File("Images/new.png");
ImageIO.write(img, "png", outputfile);
} catch (Exception e) {
System.out.println("error");
}
}
//Grayscale filter
public BufferedImage grayscale(BufferedImage img) {
for (int i = 0; i < img.getHeight(); i++) {
for (int j = 0; j < img.getWidth(); j++) {
Color c = new Color(img.getRGB(j, i));
int red = (int) (c.getRed() * 0.299);
int green = (int) (c.getGreen() * 0.587);
int blue = (int) (c.getBlue() * 0.114);
Color newColor =
new Color(
red + green + blue,
red + green + blue,
red + green + blue);
img.setRGB(j, i, newColor.getRGB());
}
}
return img;
}
public BufferedImage MatToBufferedImage(Mat frame) {
//Mat() to BufferedImage
int type = 0;
if (frame.channels() == 1) {
type = BufferedImage.TYPE_BYTE_GRAY;
} else if (frame.channels() == 3) {
type = BufferedImage.TYPE_3BYTE_BGR;
}
BufferedImage image = new BufferedImage(frame.width(), frame.height(), type);
WritableRaster raster = image.getRaster();
DataBufferByte dataBuffer = (DataBufferByte) raster.getDataBuffer();
byte[] data = dataBuffer.getData();
frame.get(0, 0, data);
return image;
}
}
When I try to rotate an image it appears that a part of the background turns black (my images are transparents)
Background white
Part of background turns black
Here's the code that rotate the image :
public BufferedImage rotate(int height, int width, BufferedImage originalImg, int angle) {
BufferedImage rotateImage = null;
try {
rotateImage = new BufferedImage(height, width, BufferedImage.TYPE_INT_RGB);
AffineTransform a90 = AffineTransform.getRotateInstance(Math.toRadians(angle), height / 2, width / 2);
AffineTransformOp op90 = new AffineTransformOp(a90, AffineTransformOp.TYPE_BILINEAR);
op90.filter(originalImg, rotateImage);
}
catch (Exception e) {
System.err.println(e);
}
return rotateImage;
}
So, I downloaded you "original" image (which is not square), modified it so it was square, run your code, got a java.awt.image.ImagingOpException: Unable to transform src image exception, changed BufferedImage.TYPE_INT_RGB to BufferedImage.TYPE_INT_ARGB and got...
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class Main {
public static void main(String[] args) {
try {
BufferedImage img = ImageIO.read(Main.class.getResource("/Block.jpg"));
BufferedImage rotate = rotate(img.getHeight(), img.getWidth(), img, 90);
JPanel panel = new JPanel();
panel.add(new JLabel(new ImageIcon(img)));
panel.add(new JLabel(new ImageIcon(rotate)));
JOptionPane.showMessageDialog(null, panel);
} catch (IOException ex) {
ex.printStackTrace();
}
}
public static BufferedImage rotate(int height, int width, BufferedImage originalImg, int angle) {
BufferedImage rotateImage = null;
try {
rotateImage = new BufferedImage(height, width, BufferedImage.TYPE_INT_ARGB);
AffineTransform a90 = AffineTransform.getRotateInstance(Math.toRadians(angle), height / 2, width / 2);
AffineTransformOp op90 = new AffineTransformOp(a90, AffineTransformOp.TYPE_BILINEAR);
op90.filter(originalImg, rotateImage);
} catch (Exception e) {
e.printStackTrace();
}
return rotateImage;
}
}
My, "gut" feeling is to also modify the rotate method, as it shouldn't need width and height values;
public static BufferedImage rotate(BufferedImage originalImg, int angle) {
BufferedImage rotateImage = null;
try {
rotateImage = new BufferedImage(originalImg.getWidth(), originalImg.getHeight(), BufferedImage.TYPE_INT_ARGB);
AffineTransform a90 = AffineTransform.getRotateInstance(Math.toRadians(angle), originalImg.getWidth() / 2, originalImg.getHeight() / 2);
AffineTransformOp op90 = new AffineTransformOp(a90, AffineTransformOp.TYPE_BILINEAR);
op90.filter(originalImg, rotateImage);
} catch (Exception e) {
e.printStackTrace();
}
return rotateImage;
}
it should be using the original image's dimensions directly. This is will highlight possible errors in your images. This also assumes that you only want to rotate the image by increments of 90 degrees
My issue: Every time I create graphics from a buffered image and then draw another buffered image to the graphics I get an image that is blank.
My code is as follows.
Graphics2D g2d = atlas.createGraphics();
// images[i] is a buffered image read the fileio
g2d.drawImage(images[i], null, x, y); // Image is not blank, been tested
g2d.dispose();
// then save image
Ironically after trying to create a self contained example which is as follows... it worked. I am not quite sure what I am doing wrong in my code and I am wondering if it is because maybe an image is not static, could an image or another variable not being static affect my drawing?
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import javax.imageio.ImageIO;
public class Main {
public static void main(String[] args) {
String FOLDER_LOCATION = "./Images/";
BufferedImage atlas = new BufferedImage(2048, 2048, BufferedImage.TYPE_INT_ARGB);
BufferedImage redSquare = readImage(FOLDER_LOCATION + "red.png");
Graphics2D g2d = atlas.createGraphics();
g2d.drawImage(redSquare, null, 0, 0);
g2d.dispose();
writeImage(atlas, FOLDER_LOCATION + "atlas.png");
}
public static BufferedImage readImage(String location) {
BufferedImage img = null;
InputStream is = null;
try {
is = new FileInputStream(location);
img = ImageIO.read(is);
} catch(Exception e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch(Exception e) {
e.printStackTrace();
}
}
return img;
}
public static void writeImage(BufferedImage bi, String location) {
try {
File file = new File(location);
ImageIO.write(bi, "png", file);
} catch(Exception e) {
e.printStackTrace();
}
}
}
After I save the image I see just a blank 2048 by 2048 image. I printed the entire image out and I get (0, 0, 0), but if I print out any of the image I am drawing to the atlas I get something like (72, 32, 283).
I am not quite sure what I am doing wrong, but my entire source code for this project is here: https://github.com/gemurdock/jTextureAtlas and the branch I am working on is here: https://github.com/gemurdock/jTextureAtlas/tree/alpha.
You have to look at the alpha branch to see my code