This question already has answers here:
Writing javafx.scene.image.Image to file?
(3 answers)
Closed 6 years ago.
I added effect and color adjustments to an image which is displayed with help of ImageView.
Now I want to save those changes to a different file. How can I perform this?
You need the snapshot functionality of the class Node paired with the fromFXImage method of SwingFXUtils.
Takes a snapshot of this node and returns the rendered image when it
is ready. CSS and layout processing will be done for the node, and any
of its children, prior to rendering it. The entire destination image
is cleared to the fill Paint specified by the SnapshotParameters.
Example:
ImageView imageViewAdjusted = new ImageView(new Image(getClass().getResource("thinking-man.jpg").toExternalForm(), 250, 250, true, true));
ColorAdjust colorAdjust = new ColorAdjust();
colorAdjust.setContrast(0.9);
imageViewAdjusted.setEffect(colorAdjust);
imageViewAdjusted.setCache(true);
imageViewAdjusted.setCacheHint(CacheHint.SPEED);
Button btnSave = new Button("Save to File");
btnSave.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
File outputFile = new File("D:/formattedPicture.png");
BufferedImage bImage = SwingFXUtils.fromFXImage(imageViewAdjusted.snapshot(null, null), null);
try {
ImageIO.write(bImage, "png", outputFile);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
});
Related
My goal is to display images that are selected from a filechooser activated by button, and add those images to my gridpane. I am able to get the right URL file path name from the file chooser in order to make a correct imageview however when doing so my gridpane does not show any images being added..
public void makeBrowseButton(Stage primaryStage) {
//attach handler
browseButton.setOnAction(new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent event) {
FileChooser fileChooser = new FileChooser(); // create object
fileChooser.getExtensionFilters()
.addAll(new FileChooser.ExtensionFilter("Image Files", "*.png", "*.jpg", "*.gif")); //filter for music files
//FileFilter filter = new FileNameExtensionFilter("JPEG file", "jpg", "jpeg");
if (!parentPath.equalsIgnoreCase(
"")) { //go to previous directory if exists
File parentPathFile = new File(parentPath);
fileChooser.setInitialDirectory(parentPathFile);
}
File selectedFile = fileChooser.showOpenDialog(primaryStage);
if (selectedFile != null) { // display the dialog box
String wholePath = selectedFile.getPath();
String name = selectedFile.getName();
String megaPath = selectedFile.getAbsolutePath();
String megaUrl;
try {
megaUrl = Paths.get(megaPath).toUri().toURL().toString();
} catch (MalformedURLException e) {
throw new IllegalArgumentException(e);
}
parentPath = selectedFile.getParent();
System.out.println("wholePath: " + wholePath);
System.out.println("parent: " + parentPath);
System.out.println("File Name: " + name);
System.out.println("megaPath: " + megaUrl);
//System.out.println("Canonical: " + Canonical);
Image newAwesomeImage = new Image(megaUrl);
paneofgridmonkeys.add(new ImageView(newAwesomeImage), 0, 0);
//ImageView view = new ImageView();
//view.setImage(newAwesomeImage);
//paneofgridmonkeys.add(view, 1, 1);
//paneofgridmonkeys.setConstraints(view, 0, 4);
//paneofgridmonkeys.add(new Label("Changed the image!"), 0, 1);
createDisplay(primaryStage);
}
}
});
}
I've tried multiple ways of insterting an images and these are the filepaths im getting:
wholePath: \\jupiter\yr1005\Desktop\20190111_1340501.jpg
parent: \\jupiter\yr1005\Desktop
File Name: 20190111_1340501.jpg
megaPath: file://jupiter/yr1005/Desktop/20190111_1340501.jpg
(im using the megapath)
basically when i choose an image from filechooser I get no error but no image is shown after selection. I just get all the print statements in return.. an idea why?
This is my create Display method:
public void createDisplay(Stage primaryStage) {
primaryStage.setTitle(this.MONKEY_TITLE);
GridPane paneofgridmonkeys = new GridPane();
paneofgridmonkeys.setAlignment(Pos.CENTER);
paneofgridmonkeys.setVgap(10);
paneofgridmonkeys.add(browseButton, 10, 10);
ScrollPane allTehFaces = new ScrollPane(paneofgridmonkeys);
allTehFaces.setFitToWidth(true);
primaryStage.setScene(new Scene(allTehFaces, 500, 500));primaryStage.show();
}
}
You're problem is in the createDisplay method; specifically this line:
GridPane paneofgridmonkeys = new GridPane();
Here you're creating a locally-scoped GridPane called paneofgridmonkeys, which must be the name of another class-level variable called paneofgridmonkeys, since it's available to makeBrowseButton. When you do this in local scope, the new instance you've created becomes the one that's used inside of that method, rather than the class-level instance; thus the class-level one isn't the one being added to your scene, and you're not seeing the changes.
i have be trying to upload the signature captured from the codename one signature to my php server.the problem is that the image uploaded is a black image.Below is my code.how can i fix this
SignatureComponent sig = new SignatureComponent();
sig.addActionListener((evt)-> {
try{
img = sig.getSignatureImage();
}catch(Exception ex){
ex.printStackTrace();
}
// Now we can do whatever we want with the image of this signature.
});
Button sv = new Button("save");
sv.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent evt) {
try {
Label it = new Label();
it.setIcon(img);
orderHome.add(it);
ImageIO imgIO= ImageIO.getImageIO();
ByteArrayOutputStream out = new ByteArrayOutputStream();
imgIO.save(img, out,ImageIO.FORMAT_JPEG, 1);
byte[] ba = out.toByteArray();
MultipartRequest request = new MultipartRequest();
String url = Global.url1 + "upload_photo.php";
request.setUrl(url);
request.addData("file",ba,"image/jpeg");
request.addArgument("order_id", order_id);
request.addArgument("customer_id", customer_id);
NetworkManager.getInstance().addToQueue(request);
and the php code
[![image uploaded][1]][1]
<?php
#SESSION_START();
require_once("../includes/functions.php");
$target_path="../uploads/";
$customer_id=$_REQUEST['customer_id'];
$order_id=$_REQUEST['order_id'];
$uid = uniqid();
$file =$uid.".jpg";
$sucess=move_uploaded_file($_FILES["file"]["tmp_name"], $target_path.$file);
the black img is the file which is uploaded to the server.the other shows the screenshot of the running app.i would like to upload the signature as shown in the screenshot
The signature generates a translucent image. JavaSE has some issues with saving translucent images as JPEGs and thus PNG works well. Another alternative would be to create an opaque image and save that as a JPEG e.g.:
Image myImage = Image.create(img.getWidth(), img.getHeight());
myImage.getGraphics().drawImage(img, 0, 0);
The new myImage will be opaque with the white color background.
In my JavaFX application I use a TreeView. The single TreeItems contain an image. Unfortunately, the image is shown only once.
The code for loading the image looks like the following. It is called every time the TreeView changes. The Images are cached in a Map ("icons"). Thus, a new ImageView is created every time.
public final ImageView getImage(final String imageConstant) {
final Image img;
if (icons.containsKey(imageConstant)) {
img = icons.get(imageConstant);
}
else {
if (isRunFromJAR) {
img = new Image("/path/" + imageConstant, iconSizeWidth,
iconSizeHeight, false, false);
}
else {
img = new Image(getClass().getResourceAsStream(imageConstant), iconSizeWidth,
iconSizeHeight, false, false);
}
icons.put(imageConstant, img);
}
return new ImageView(img);
In the updateItem method of my TreeCells, the ImageView returned above is stored into a field called icon. The field is used in the following code, also from updateItem:
if (icon == null) {
setGraphic(label);
}
else {
final HBox hbox = new HBox(ICON_SPACING);
final Label iconLabel = new Label("", icon);
hbox.getChildren().addAll(iconLabel, label);
setGraphic(hbox);
}
But for some reason, the problem shown in the gif occurs.
Update
Actually, the ImageViews were cached internally, which led to de-duplication. Using multiple ImageViews is the solution.
the ImageView returned above is stored into a field called icon.The field is used in the following code...
The ImageView is type of Node. A Node can only have one parent at a time!
So don't store/cache a ImageView(-Node). Create new ImageView-Nodes.
Edit:
As pointed out in the comments by James_D:
...you can use the same Image(-Object) for every ImageView...
This question already has an answer here:
JavaFX I want to save Chart-Image completely
(1 answer)
Closed 3 years ago.
I'm trying to get a snapshot of my "Java pop up window". The "Java window" looks like:
http://www.directupload.net/file/d/3616/kajnpeag_png.htm
However the snapshot looks like:
http://www.directupload.net/file/d/3616/cx47ga2o_png.htm
Sorry for the links, but I'm not allowed to post images yet.
So on the y-axis the autorange is missing and on the x-axis the dates are missing. Why didn't get my snapshot-function the whole picture? Do you have any suggestions/ideas how to solve this issue? For any help I would be grateful.
Code snapshot function:
public void saveAsPng(Scene scene) {
WritableImage image = scene.snapshot(null);
File file = new File("chart.png");
try {
ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", file);
} catch (IOException ex) {
Logger.getLogger(Server_Application.class.getName()).log(Level.SEVERE, null, ex);
}
}
The calling function:
#Override
public void start(Stage stage) throws Exception {
...
Parent root = FXMLLoader.load(getClass().getResource("MainPicture.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
Server_Application.serverApp.saveAsPng(scene);
...
}
I got the solution:
You have to deactivate the animation of the chart:
lineChart.setAnimated(false);
I am working on a JFrame/panel that will contain a button. When the user clicks the button, I want an image (which will be stored in the computer hard disk beforehand) to open on the front screen.
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//here i want a code that will somehow open the image from a given directory
}});
Any suggestions on how to go about this ? I have to tell where the image is stored and trigger a virtual 'double click' for the image to pop up on the front screen. Is that even possible using java to synchronize such computer functions?
I don't know a very short way, but I would use something like this (as qick hack to get an impression):
try {
// this is a new frame, where the picture should be shown
final JFrame showPictureFrame = new JFrame("Title");
// we will put the picture into this label
JLabel pictureLabel = new JLabel();
/* The following will read the image */
// you should get your picture-path in another way. e.g. with a JFileChooser
String path = "C:\\Users\\Public\\Pictures\\Sample Pictures\\Koala.jpg";
URL url = new File(path).toURI().toURL();
BufferedImage img = ImageIO.read(url);
/* until here */
// add the image as ImageIcon to the label
pictureLabel.setIcon(new ImageIcon(img));
// add the label to the frame
showPictureFrame.add(pictureLabel);
// pack everything (does many stuff. e.g. resizes the frame to fit the image)
showPictureFrame.pack();
//this is how you should open a new Frame or Dialog, but only using showPictureFrame.setVisible(true); would also work.
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
showPictureFrame.setVisible(true);
}
});
} catch (IOException ex) {
System.err.println("Some IOException accured (did you set the right path?): ");
System.err.println(ex.getMessage());
}
I think this will work ...
Code:
process = new ProcessBuilder("mspaint","yourFileName.jpeg").start();
This will open your image file with mspaint.....
and also use *Java Advanced Imaging (JAI)*
Try this code
try
{
// the line that reads the image file
BufferedImage image;
// work with the image here ...
image = ImageIO.read(new File("C://Users//Neo//Desktop//arduino.jpg"));
jLabel1.setIcon(new ImageIcon(image));
}
catch (IOException e)
{
// log the exception
// re-throw if desired
}
I'm not sure but try this...
try
{
JLabel picture=new JLabel();
ImageIcon ic=new ImageIcon(Toolkit.getDefaultToolkit().getImage(getClass().getResource("C:\\Users\\Desktop\\xyz.jpg")));
picture.setIcon(ic);
}
catch(Exception)
{
}