Trying to draw a graph but getting Null on weigths - java

I'm trying to create an image file of a graph with vertices,edges and weigths with JgraphX and mxGraph.
I'm new to this thing of JGraph and stuff and found a tutorial to do this.
But I can't understand why when it creates the image, it shows the vertices and edges good but the weights are "Null".
I'll post the code below together with a image.
import com.mxgraph.layout.mxCircleLayout;
import com.mxgraph.layout.mxIGraphLayout;
import com.mxgraph.util.mxCellRenderer;
import org.jgrapht.ext.JGraphXAdapter;
import org.jgrapht.graph.DefaultDirectedGraph;
import org.jgrapht.graph.DefaultDirectedWeightedGraph;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.*;
import org.jgrapht.graph.DefaultUndirectedWeightedGraph;
import org.jgrapht.traverse.BreadthFirstIterator;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class JgraphTest{
DefaultDirectedWeightedGraph<String, DefaultEdge> g = new DefaultDirectedWeightedGraph<>(DefaultEdge.class);
BreadthFirstIterator bfs;
public void crearGrafo(){
g.addVertex("Ninja1");
g.addVertex("Ninja2");
g.addVertex("Ninja3");
g.addVertex("Ninja5");
g.addVertex("Ninja8");
g.addEdge("Ninja1","Ninja2");
g.addEdge("Ninja2","Ninja1");
g.addEdge("Ninja8","Ninja3");
g.addEdge("Ninja3","Ninja5");
g.setEdgeWeight("Ninja1","Ninja2",12);
g.setEdgeWeight("Ninja2","Ninja1",2);
g.setEdgeWeight("Ninja8","Ninja3",10);
}
public void mostrarGrafo() throws IOException {
JGraphXAdapter<String, DefaultEdge> graphXAdapter = new JGraphXAdapter<>(g);
mxIGraphLayout layout = new mxCircleLayout(graphXAdapter);
layout.execute(graphXAdapter.getDefaultParent());
BufferedImage image = mxCellRenderer.createBufferedImage(graphXAdapter, null, 2, Color.white, true, null);
File imgFile = new File("src/graph.jpg");
ImageIO.write(image, "JPG",imgFile );
}
}
Image created after executing the algorithm
Thank you everyone and I hope I didn't miss any information, please let me know if I forgot to post something.

Related

Colors of image's pixels change when rotating image using java OpenCV

hope you're doing well.
Actually, i'm facing a problem when trying to rotate an image using Core.rotate Class of OpenCV.
the colors of the image pixels keep changing every time i click the rotation Button.
Can anyone please help me fixing this problem ?
Thanks in advance.
I've tried to change the colors of the image using Imgproc.cvtColor but it didn't work.
This is the code :
`
package application;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.imgcodecs.Imgcodecs;
import javafx.embed.swing.SwingFXUtils;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
public class SampleController {
#FXML
private ImageView myimageview;
#FXML
private Button showimageButton, rotateButton;
#FXML
void rotateButtonClicked(ActionEvent event) throws Exception {
BufferedImage image = SwingFXUtils.fromFXImage(myimageview.getImage(), null);
Mat src = BufferedImage2Mat(image);
Core.rotate(src, src, Core.ROTATE_90_CLOCKWISE);
image = Mat2BufferedImage(src);
try {
Image converted_image = SwingFXUtils.toFXImage(image, null);
myimageview.setImage(converted_image);
}
catch (Exception e) {
System.out.println(e);
}
}
public Mat BufferedImage2Mat(BufferedImage image) throws IOException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", byteArrayOutputStream);
byteArrayOutputStream.flush();
return Imgcodecs.imdecode(new MatOfByte(byteArrayOutputStream.toByteArray()), Imgcodecs.CV_LOAD_IMAGE_UNCHANGED);
}
static BufferedImage Mat2BufferedImage(Mat matrix)throws Exception {
MatOfByte mob=new MatOfByte();
Imgcodecs.imencode(".jpg", matrix, mob);
byte ba[]=mob.toArray();
BufferedImage bi=ImageIO.read(new ByteArrayInputStream(ba));
return bi;
}
#FXML
void showimageButtonClicked(ActionEvent event) {
Image im = new Image("file:///C:\\Users\\poste\\eclipse-workspace\\dragImage\\Images\\temp.jpg");
myimageview.setImage(im);
}
}
`

Libgdx Filling Screen With Image

I'm new to Libgdx and am having some problems filling an image to the entire screen. If I import a 1900x1200 image, it fills the screen, but if instead the image is 1024x512, the image is not stretched to the screen. The following is the code I've used. I thought that ''background.setSize(stageWidth, stageHeight)'' would scale the image to the screen but this doesn't happen. Could you please inform me of what I'm doing wrong? I've tried toggling with the ''setFillParent'' (as mentioned in another post) but it still doesn't work. Here's also included a screenshot of what currently appears (both on the Desktop implementation and Android): http://tinypic.com/r/b7j20z/8
Thank You for your help!
package com.mygdx.game;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;
import com.badlogic.gdx.scenes.scene2d.actions.MoveToAction;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.utils.viewport.FitViewport;
import com.badlogic.gdx.utils.viewport.StretchViewport;
import com.badlogic.gdx.utils.viewport.Viewport;
public class MyGdxGame implements ApplicationListener{
private Stage stage;
#Override
public void create() {
stage = new Stage();
float stageHeight = Gdx.graphics.getHeight();
float stageWidth = Gdx.graphics.getWidth();
// Background
Texture board = new Texture(Gdx.files.internal("data/frame.png"));
Image background = new Image(board);
background.setOrigin(0, 0);
background.setSize(stageWidth, stageHeight);
background.rotateBy(0);
background.setPosition(0, 0);
stage.addActor(background);
}
#Override
public void dispose() {
stage.dispose();
}
#Override
public void render() {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
stage.act(Gdx.graphics.getDeltaTime());
stage.draw();
}
#Override
public void resize(int width, int height) {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
}
After thinking about it for a bit, the most likely cause of your problem is that you're adding your image directly to the root of the stage. The root of the stage is a Group that doesn't handle any kind of layout managing, which is probably why your image isn't sized correctly.
I'd recommend instead that you create a Table, and then use setFillParent() so it takes up the entire screen. You can then simply use the Table's built in function, table.background(drawable), to set a background. However, you have to keep in mind that a Texture doesn't count as drawable for the table, so you have to use the class TextureRegionDrawable to get a valid drawable for the background. Here's an example:
table.background(new TextureRegionDrawable(new TextureRegion(board)));

Fastest method for blurring an image in java

Edit I'm using Eclipse ADT bundle but when I try importing the library in the suggested answer above it doesn't work.
I'm using a combination of LibGDX and Java (90-99% java) to blur an image. The blur works but it takes nearly a second to take a screenshot, save it, access it, blur it, save it, and re-access it. I can't do much pre-processing because it takes a screenshot of the game to blur. Here is what I'm using currently for blurring: (I'll put drawing and screenshots up if you need to see them, but I think the issue lies in the blurring of an 800x480 png.)
import java.awt.image.BufferedImage;
import java.awt.image.BufferedImageOp;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
public class Blur {
private static BufferedImage mshi;
private BufferedImage databuf;
private static int blurRad = 300;
public static void createBlur(FileHandle file) throws IOException {
mshi = ImageIO.read(file.file());
BufferedImage databuf = new BufferedImage(mshi.getWidth(null),
mshi.getHeight(null),
BufferedImage.TYPE_INT_BGR);
java.awt.Graphics g = databuf.getGraphics();
g.drawImage(mshi, 455, 255, null);
float[] blurKernel = new float[blurRad*blurRad];
for(int i =0; i<blurRad*blurRad; i++) {
blurKernel[i] = 1.0f/256.0f;
}
BufferedImageOp op = new ConvolveOp( new Kernel(20, 20, blurKernel), ConvolveOp.EDGE_ZERO_FILL, null );
mshi = op.filter(mshi, databuf);
g.dispose();
File outputfile = Gdx.files.local("Blur.png").file();
ImageIO.write(mshi, "png", outputfile);
}
}

Java does not load embedded Images

package common;
import java.awt.image.BufferedImage;
import java.io.InputStream;
import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class ResourcesToAccess {
public static Icon sharedAbstractDownIcon;
public static Icon sharedAbstractPlayIcon;
public static Icon sharedAbstractPauseIcon;
public static Icon sharedAbstractBlackCursor;
public static Icon sharedAbstractWhiteCursor;
public ResourcesToAccess(){
InputStream is = this.getClass().getClassLoader().getResourceAsStream("/src/images/blackCursor.png");
try{
BufferedImage bi = ImageIO.read(is);
sharedAbstractBlackCursor = (Icon) new ImageIcon(bi);
new JFrame().add(new JLabel(sharedAbstractBlackCursor)).setVisible(true);
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) {
new ResourcesToAccess();
}
}
I am using this code to see whether the PNG images can be properly loaded to create JLabels, Icons, etc but I get the error that:
java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.read(Unknown Source)
at common.ResourcesToAccess.<init>(ResourcesToAccess.java:21)
at common.ResourcesToAccess.main(ResourcesToAccess.java:29)
Why do I see that error message?
try with
this.getClass().getClassLoader().getResourceAsStream("images/blackCursor.png")
it is looking in your classpath so no more src directory there

How to customize the renders in prefuse. Problem in customize images in prefuse layout

HI all,
I have written a java application to show the images in different layouts. I am able to show it different layout correctly but some times the images are overlapped. In my application having more than 20/30 nodes and couple of nodes having 6 to 10 edges. The images size are 50*50. Because of the 10 edges, the nodes will overlapped i.e images will overlapped on another images. How can I solve the problem?
Any help will be highly appreciated.
My code is given below
import javax.swing.JFrame;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.util.;
import java.io.;
import java.awt.Font;
import prefuse.Constants;
import prefuse.Display;
import prefuse.Visualization;
import prefuse.action.ActionList;
import prefuse.action.RepaintAction;
import prefuse.action.assignment.ColorAction;
import prefuse.action.assignment.FontAction;
import prefuse.action.assignment.DataColorAction;
import prefuse.action.layout.graph.ForceDirectedLayout;
import prefuse.action.layout.graph.;
import prefuse.action.layout.;
import prefuse.activity.Activity;
import prefuse.controls.DragControl;
import prefuse.controls.PanControl;
import prefuse.controls.ZoomControl;
import prefuse.data.Graph;
import prefuse.data.io.DataIOException;
import prefuse.data.io.GraphMLReader;
import prefuse.render.DefaultRendererFactory;
import prefuse.render.LabelRenderer;
import prefuse.util.ColorLib;
import prefuse.visual.VisualItem;
import prefuse.visual.*;
import prefuse.util.FontLib;
import prefuse.action.assignment.DataSizeAction;
import prefuse.data.*;
import prefuse.render.ImageFactory;
public class LayoutExample {
public static void main(String[] argv) throws Exception {
Graph graph = null;
try {
graph = new GraphMLReader().readGraph("/graphs.xml");
} catch ( DataIOException e ) {
e.printStackTrace();
System.err.println("Error loading graph. Exiting...");
System.exit(1);
}
ImageFactory imageFactory = new ImageFactory(100,100);
try
{
//load images and construct imageFactory.
String images[] = new String[3];
images[0] = "data/images/switch.png";
images[1] = "data/images/ip_network.png";
images[2] = "data/images/router.png";
String[] names = new String[] {"Switch","Network","Router"};
BufferedImage img = null;
for(int i=0; i < images.length ; i++)
{
try {
img = ImageIO.read(new File(images[i]));
imageFactory.addImage(names[i],img);
}
catch (IOException e){
}
}
}
catch(Exception exp)
{
}
Visualization vis = new Visualization();
vis.add("graph", graph);
LabelRenderer nodeRenderer = new LabelRenderer("name", "type");
nodeRenderer.setVerticalAlignment(Constants.BOTTOM);
nodeRenderer.setHorizontalPadding(0);
nodeRenderer.setVerticalPadding(0);
nodeRenderer.setImagePosition(Constants.TOP);
nodeRenderer.setMaxImageDimensions(100,100);
DefaultRendererFactory drf = new DefaultRendererFactory();
drf.setDefaultRenderer(nodeRenderer);
vis.setRendererFactory(drf);
ColorAction nText = new ColorAction("graph.nodes", VisualItem.TEXTCOLOR);
nText.setDefaultColor(ColorLib.gray(100));
ColorAction nEdges = new ColorAction("graph.edges", VisualItem.STROKECOLOR);
nEdges.setDefaultColor(ColorLib.gray(100));
// bundle the color actions
ActionList draw = new ActionList();
//MAD - changing the size of the nodes dependent on the weight of the people
final DataSizeAction dsa = new DataSizeAction("graph.nodes","size");
draw.add(dsa);
draw.add(nText);
draw.add(new FontAction("graph.nodes", FontLib.getFont("Tahoma",Font.BOLD, 12)));
draw.add(nEdges);
vis.putAction("draw", draw);
ActionList layout = new ActionList(Activity.DEFAULT_STEP_TIME);
BalloonTreeLayout balloonlayout = new BalloonTreeLayout("graph",50);
layout.add(balloonlayout);
Display d = new Display(vis);
vis.putAction("layout", layout);
// start up the animated layout
vis.run("draw");
vis.run("layout");
d.addControlListener(new DragControl());
// pan with left-click drag on background
d.addControlListener(new PanControl());
// zoom with right-click drag
d.addControlListener(new ZoomControl());
// -- 6. launch the visualization -------------------------------------
// create a new window to hold the visualization
JFrame frame = new JFrame("prefuse example");
// ensure application exits when window is closed
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(d);
frame.pack(); // layout components in window
frame.setVisible(true); // show the window
}
}
Thanks
R.Ravikumar

Categories