How to convert PlanarImage or BufferedImage (JAI) to Image (JavaFX) - image-processing

I am trying to change the image represented in an ImageView instance, after manipulating it with JAI. JAI can output a PlanarImage, RenderedImage(non-awt), or BufferedImage(non-awt), but these are not valid types for ImageView construction.
import java.awt.image.renderable.ParameterBlock;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.image.ImageView;
import javafx.scene.image.Image;
import javafx.stage.Stage;
import javax.media.jai.JAI;
import javax.media.jai.PlanarImage;
import javax.media.jai.Interpolation;
public class A11 extends Application{
int zoom = 100;
ImageView img = new ImageView();
Image src = new Image("file.bmp");
public static void main(String args[]){
launch(args); // start application
}
#Override
public void start(Stage window){
ParameterBlock pb = new ParameterBlock();
pb.addSource(src); // source Image
pb.add(zoom/100); // xScale
pb.add(zoom/100); // yScale
pb.add(0.0F); // xTranslate
pb.add(0.0F); // yTranslate
pb.add(Interpolation.getInstance(Interpolation.INTERP_BICUBIC));
PlanarImage dest = JAI.create("scale", pb, null);
// NEED TO CONVERT 'dest' TO 'destImage' HERE
ImageView frame = new ImageView(destImage);
ScrollPane pane = new ScrollPane(frame);
window.setScene(new Scene(pane,800,600));
window.show();
}
}

Related

Java process physical memory increases continuously

I've run into a situation where a simple canvas
Drawing app shows a gradual increase in physical
Memory usage over time until it hits about 80% mark
And tries to maintain the process memory usage around
That number (that is the %MEM column when 'top' is run, 64bit Linux box). Of course by that point page swapping kicks in. I've tried to limit memory usage by using -Xmx10m -Xms10m and even -XX:+UseG1GC but nothing appears to make a difference.
Just a side note, I've even tried the StockLineChartApp example shipped with oracle jdk Javafx examples and it displays a physical memory usage increase as well. I'm using jdk1.8.0_102.
Any feedback regarding this issue would be very helpful. Thanks.
//
package test8;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import javafx.util.Duration;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.animation.Animation;
public class Test8 extends Application {
GraphicsContext gc;
double x;
double y;
#Override
public void start(Stage primaryStage) {
try {
Group root = new Group();
Scene s = new Scene(root, 600, 400, Color.BLACK);
final Canvas canvas = new Canvas(500,300);
gc = canvas.getGraphicsContext2D();
root.getChildren().add(canvas);
Pane pane = new Pane();
pane.getChildren().add(root);
Scene scene = new Scene(pane);
primaryStage.setTitle("canvas test");
primaryStage.setScene(scene);
primaryStage.show();
gc.beginPath();
x = 0.0;
y = 0.0;
EventHandler onFinished = new EventHandler<ActionEvent>() {
public void handle(ActionEvent t) {
y = (y<canvas.getHeight()) ? (y + 10.0) : 0.0;
x = (x<canvas.getWidth()) ? (x + 5.0) : 0.0;
gc.lineTo(x,y);
gc.stroke();
if (x==0.0) gc.beginPath();
}
};
final Timeline timeline = new Timeline();
timeline.setCycleCount(Animation.INDEFINITE);
timeline.setAutoReverse(true);
timeline.getKeyFrames().add(new KeyFrame(Duration.millis(40), onFinished));
timeline.play();
} catch (Exception e) {
System.out.println("Application start Exception");
} finally {
}
}
public static void main(String[] args) {
launch(args);
}
}

Put a String on the edge of JUNG graph

I'm trying to put a String text to an edge of a JUNG tree graph. See bellow example.
What I tried is to simply add this line:
graph.addEdge("arrow", "Vmain", "Vsecond");
... but without any results (see bellow screenshot). I need some advices please.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.apache.commons.collections15.Factory;
import edu.uci.ics.jung.algorithms.layout.TreeLayout;
import edu.uci.ics.jung.graph.DirectedGraph;
import edu.uci.ics.jung.graph.DirectedSparseMultigraph;
import edu.uci.ics.jung.graph.Forest;
import edu.uci.ics.jung.graph.DelegateForest;
import edu.uci.ics.jung.graph.DelegateTree;
import edu.uci.ics.jung.graph.Tree;
import edu.uci.ics.jung.visualization.GraphZoomScrollPane;
import edu.uci.ics.jung.visualization.VisualizationViewer;
import edu.uci.ics.jung.visualization.control.CrossoverScalingControl;
import edu.uci.ics.jung.visualization.control.DefaultModalGraphMouse;
import edu.uci.ics.jung.visualization.control.ModalGraphMouse;
import edu.uci.ics.jung.visualization.control.ScalingControl;
import edu.uci.ics.jung.visualization.decorators.EdgeShape;
import edu.uci.ics.jung.visualization.decorators.ToStringLabeller;
public class TreeVisualiser extends JApplet {
Forest<String, String> graph;
Factory<DirectedGraph<String, String>> graphFactory = new Factory<DirectedGraph<String, String>>() {
public DirectedGraph<String, String> create() {
return new DirectedSparseMultigraph<String, String>();
}
};
Factory<Tree<String, String>> treeFactory = new Factory<Tree<String, String>>() {
public Tree<String, String> create() {
return new DelegateTree<String, String>(graphFactory);
}
};
VisualizationViewer<String, String> vv;
String root;
TreeLayout<String, String> treeLayout;
#SuppressWarnings({"rawtypes", "unchecked"})
public TreeVisualiser() {
// create a simple graph for the demo
graph = new DelegateForest<String, String>();
createTree();
treeLayout = new TreeLayout<String, String>(graph);
vv = new VisualizationViewer<String, String>(treeLayout, new Dimension(600, 600));
vv.setBackground(Color.white);
vv.getRenderContext().setEdgeShapeTransformer(new EdgeShape.Line());
vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller());
// add a listener for ToolTips
vv.setVertexToolTipTransformer(new ToStringLabeller());
Container content = getContentPane();
final GraphZoomScrollPane panel = new GraphZoomScrollPane(vv);
content.add(panel);
final DefaultModalGraphMouse graphMouse = new DefaultModalGraphMouse();
vv.setGraphMouse(graphMouse);
JComboBox modeBox = graphMouse.getModeComboBox();
modeBox.addItemListener(graphMouse.getModeListener());
graphMouse.setMode(ModalGraphMouse.Mode.TRANSFORMING);
final ScalingControl scaler = new CrossoverScalingControl();
JButton plus = new JButton("+");
plus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
scaler.scale(vv, 1.1f, vv.getCenter());
}
});
JButton minus = new JButton("-");
minus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
scaler.scale(vv, 1 / 1.1f, vv.getCenter());
}
});
JPanel scaleGrid = new JPanel(new GridLayout(1, 0));
scaleGrid.setBorder(BorderFactory.createTitledBorder("Zoom"));
JPanel controls = new JPanel();
scaleGrid.add(plus);
scaleGrid.add(minus);
controls.add(scaleGrid);
controls.add(modeBox);
content.add(controls, BorderLayout.SOUTH);
}
private void createTree() {
graph.addEdge("arrow", "Vmain", "Vsecond");
}
public static void main(String[] args) {
JFrame frame = new JFrame();
Container content = frame.getContentPane();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
content.add(new TreeVisualiser());
frame.pack();
frame.setVisible(true);
}
}
Oh, I missed this line of code. Now it is working as I want.
vv.getRenderContext().setEdgeLabelTransformer(new ToStringLabeller());

AlivePdf create a map chart

I'm building a pure actionscript project and would like to create a pdf with an map chart of the world to display my data.
It's possible to create a map and save as image and then embed in pdf with alivepdf?
package
{
import MyButton;
import flash.display.*;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.external.*;
import flash.net.*;
import flash.net.FileReference;
import flash.system.Security;
import flash.utils.ByteArray;
import org.alivepdf.display.*;
import org.alivepdf.fonts.*;
import org.alivepdf.layout.*;
import org.alivepdf.pdf.*;
import org.alivepdf.saving.*;
public class WorldTest extends Sprite
{
private var saveButton:MyButton = new MyButton();
// declared of logo or imagen on top of the PDF's document.
[Embed(source="FCMap_World.swf", mimeType="application/octet-stream" )]
protected var jpgBytes:Class;
protected var pdf:PDF;
public function WorldTest() {
saveButton.y = 0;
addChild(saveButton);
this.addEventListener(MouseEvent.CLICK, onMouseClickEvent);
}
protected function onMouseClickEvent(event:Event):void{
pdf = new PDF(Orientation.LANDSCAPE, Unit.MM, Size.LETTER);
pdf.setDisplayMode(Display.FULL_WIDTH);
pdf.addPage();
pdf.addImage(new jpgBytes() as DisplayObject, null, 0, 0, 0);
var bytes:ByteArray = pdf.save(Method.LOCAL);
var file:FileReference = new FileReference();
file.save(bytes, "myPDF.pdf");
}
}
}
It seems like you are trying to add swf file as image.
You need to make an image from it first.
var map : MovieClip = new jpgBytes();
var bitmapData : BitmapData = new BitmapData(map.width, map.height);
bitmapData.draw(map);
var bitmap : Bitmap = new Bitmap(bitmapData);
You can try to use another library called PDFcase for creating pdf in ActionScript.
This example shows how to add images to pdf.

Run JesterRecommenderEvaluationRunner, but get no results of evaluation

I downloaded the Jester example code in Mahout, and tries to run it on jester dataset to see the evaluation results. the running is done successfully, but the console only has the results:
log4j:WARN No appenders could be found for logger (org.apache.mahout.cf.taste.impl.model.file.FileDataModel).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
I expect to see the evaluation score range from 0 to 10. any one can help me found out how to get the score?
I am using mahout-core-0.6.jar and the following is the code:
JesterDataModel.java:
package Jester;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.regex.Pattern;
import com.google.common.collect.Lists;
import org.apache.mahout.cf.taste.example.grouplens.GroupLensDataModel;
import org.apache.mahout.cf.taste.impl.common.FastByIDMap;
import org.apache.mahout.cf.taste.impl.model.GenericDataModel;
import org.apache.mahout.cf.taste.impl.model.GenericPreference;
import org.apache.mahout.cf.taste.impl.model.file.FileDataModel;
import org.apache.mahout.cf.taste.model.DataModel;
import org.apache.mahout.cf.taste.model.Preference;
import org.apache.mahout.common.iterator.FileLineIterator;
//import org.apache.mahout.cf.taste.impl.common.FileLineIterable;
public final class JesterDataModel extends FileDataModel {
private static final Pattern COMMA_PATTERN = Pattern.compile(",");
private long userBeingRead;
public JesterDataModel() throws IOException {
this(GroupLensDataModel.readResourceToTempFile("\\jester-data-1.csv"));
}
public JesterDataModel(File ratingsFile) throws IOException {
super(ratingsFile);
}
#Override
public void reload() {
userBeingRead = 0;
super.reload();
}
#Override
protected DataModel buildModel() throws IOException {
FastByIDMap<Collection<Preference>> data = new FastByIDMap<Collection<Preference>> ();
FileLineIterator iterator = new FileLineIterator(getDataFile(), false);
FastByIDMap<FastByIDMap<Long>> timestamps = new FastByIDMap<FastByIDMap<Long>>();
processFile(iterator, data, timestamps, false);
return new GenericDataModel(GenericDataModel.toDataMap(data, true));
}
#Override
protected void processLine(String line,
FastByIDMap<?> rawData,
FastByIDMap<FastByIDMap<Long>> timestamps,
boolean fromPriorData) {
FastByIDMap<Collection<Preference>> data = (FastByIDMap<Collection<Preference>>) rawData;
String[] jokePrefs = COMMA_PATTERN.split(line);
int count = Integer.parseInt(jokePrefs[0]);
Collection<Preference> prefs = Lists.newArrayListWithCapacity(count);
for (int itemID = 1; itemID < jokePrefs.length; itemID++) { // yes skip first one, just a count
String jokePref = jokePrefs[itemID];
if (!"99".equals(jokePref)) {
float jokePrefValue = Float.parseFloat(jokePref);
prefs.add(new GenericPreference(userBeingRead, itemID, jokePrefValue));
}
}
data.put(userBeingRead, prefs);
userBeingRead++;
}
}
JesterRecommenderEvaluatorRunner.java
package Jester;
import org.apache.mahout.cf.taste.common.TasteException;
import org.apache.mahout.cf.taste.eval.RecommenderEvaluator;
import org.apache.mahout.cf.taste.impl.eval.AverageAbsoluteDifferenceRecommenderEvaluator;
import org.apache.mahout.cf.taste.model.DataModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
public final class JesterRecommenderEvaluatorRunner {
private static final Logger log = LoggerFactory.getLogger(JesterRecommenderEvaluatorRunner.class);
private JesterRecommenderEvaluatorRunner() {
// do nothing
}
public static void main(String... args) throws IOException, TasteException {
RecommenderEvaluator evaluator = new AverageAbsoluteDifferenceRecommenderEvaluator();
DataModel model = new JesterDataModel();
double evaluation = evaluator.evaluate(new JesterRecommenderBuilder(),
null,
model,
0.9,
1.0);
log.info(String.valueOf(evaluation));
}
}
Mahout 0.7 is old, and 0.6 is very old. Use at least 0.7, or better, later from SVN.
I think the problem is exactly what you identified: you don't have any slf4j bindings in your classpath. If you use the ".job" files in Mahout you will have all dependencies packages. Then you will actually see output.

How to make an overlay on top of JavaFX 2 webview?

Is it possible to to overlay any JavaFx2 widgets or canvas on top of a JavaFX 2 webview?
I want to generate a transparent heatmap by means of JavaFX 2 on top of a webview.
Adding overlay is very easy: just put webview and any pane to StackPane.
Another story is to synchronize overlay and webview data. To achieve that you need to ask webview for object coordinates through javascript. Here is an example which finds stackoverflow question area and marks it on overlay:
public class WebOverlay extends Application {
#Override
public void start(Stage stage) {
StackPane root = new StackPane();
WebView webView = new WebView();
final WebEngine webEngine = webView.getEngine();
Canvas overlay = new Canvas(600,600);
overlay.setOpacity(0.5);
final GraphicsContext gc = overlay.getGraphicsContext2D();
gc.setFill(Color.RED);
root.getChildren().addAll(webView, overlay);
stage.setScene(new Scene(root, 600, 600));
webEngine.getLoadWorker().workDoneProperty().addListener((observable, oldValue, newValue) -> {
if (newValue.intValue() == 100) {
// find coordinates by javascript call
JSObject bounds = (JSObject)webEngine.executeScript("document.getElementsByClassName('question-hyperlink')[0].getBoundingClientRect()");
Number right = (Number)bounds.getMember("right");
Number top = (Number)bounds.getMember("top");
Number bottom = (Number)bounds.getMember("bottom");
Number left = (Number)bounds.getMember("left");
// paint on overlaing canvas
gc.rect(left.doubleValue(), top.doubleValue(), right.doubleValue(), bottom.doubleValue());
gc.fill();
}
});
webEngine.load("http://stackoverflow.com/questions/10894903/how-to-make-an-overlay-on-top-of-javafx-2-webview");
stage.show();
}
public static void main(String[] args) { launch(); }
}
Do you mean something like this:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.RectangleBuilder;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.scene.text.TextBuilder;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
public class Demo extends Application {
#Override
public void start(Stage primaryStage) {
WebView webView = new WebView();
webView.getEngine().load("http://www.google.com");
StackPane root = new StackPane();
root.getChildren().addAll(webView, getOverlay());
primaryStage.setScene(new Scene(root, 300, 250));
primaryStage.show();
}
private Pane getOverlay() {
StackPane p = new StackPane();
Rectangle r = RectangleBuilder.create()
.height(100).width(100)
.arcHeight(40).arcWidth(40)
.stroke(Color.RED)
.fill(Color.web("red", 0.1))
.build();
Text txt=TextBuilder.create().text("Overlay")
.font(Font.font("Arial", FontWeight.BOLD, 18))
.fill(Color.BLUE)
.build();
p.getChildren().addAll(r, txt);
return p;
}
public static void main(String[] args) {
launch(args);
}
}

Resources