JGraphT Image Creation - eclipse

I need to create an Directed Graph and an image displaying this Graph.
I tried using DirectedGraph which works just fine to create the Graph, it´s internally stored correctly, I tested this but I fail in creating an image from it to Display in an E4 RCP Application.
This is my code:
import org.jgraph.JGraph;
import org.jgrapht.DirectedGraph;
import org.jgrapht.ext.JGraphModelAdapter;
import org.jgrapht.graph.DefaultDirectedGraph;
import org.jgrapht.graph.DefaultEdge;
DirectedGraph <String, DefaultEdge> graph = new DefaultDirectedGraph<String, DefaultEdge>(DefaultEdge.class);
addVertexes();
addEdges();
//Create image from graph
JGraphModelAdapter<String, DefaultEdge> graphModel = new JGraphModelAdapter<String, DefaultEdge>(graph);
JGraph jgraph = new JGraph (graphModel);
BufferedImage img = jgraph.getImage(Color.WHITE, 5);
but apparently img is always null. Why is that so and how can I change this to work properly?

Just read about JGraphX and tried using that, so for me it works just fine! This is an example of my code now (example with reduced Vertices and Edges).
mxGraph graphMx = new mxGraph();
graphMx.insertVertex(graphMx.getDefaultParent(), "Start", "Start", 0.0, 0.0, 50.0, 30.0, "rounded");
graphMx.insertVertex(graphMx.getDefaultParent(), "Ende", "Ende", 0.0, 0.0, 50.0, 30.0, "rounded");
graphMx.insertEdge(graphMx.getDefaultParent(), null, "", ((mxGraphModel)graphMx.getModel()).getCell("Start"), ((mxGraphModel)graphMx.getModel()).getCell("Ende"));
mxIGraphLayout layout = new mxHierarchicalLayout(graphMx);
layout.execute(graphMx.getDefaultParent());
BufferedImage image = mxCellRenderer.createBufferedImage(graphMx, null, 1, Color.WHITE, true, null);
return image;

My answer is similar to #HexFlex, but i got this to work the same way, although i'm not sure how to customize the drawing:
String GRAPH_FILE_PATH = "somwhere/u/want.png";
public static <V, E> File drawGraph(Graph<V, E> graph) throws IOException {
JGraphXAdapter<V, E> graphAdapter = new JGraphXAdapter<V, E>(graph);
mxIGraphLayout layout = new mxCircleLayout(graphAdapter);
layout.execute(graphAdapter.getDefaultParent());
BufferedImage image = mxCellRenderer.createBufferedImage(graphAdapter, null, 2, new Color(0f,0f,0f,.5f), true, null);
File imgFile = new File(GRAPH_FILE_PATH);
ImageIO.write(image, "PNG", imgFile);
return imgFile;
}
Edit:
Btw, the code is from https://www.baeldung.com/jgrapht, i just refactored it into a function

you can also put it on a JFRAME and generate an image from that frame.
-Jan

Related

saving modified data in pdf itextsharp

I have created a pdf using itextsharp which contains some editable fields, when the service is called the pdf is created. But the problem what I am facing is, if i am changing anything in the pdf and downloading it then the changes are not saved. Also i want to open the pdf in a new tab through server side.
Code what I am using is:
public static String[] LANGUAGES_gc = { "English", "Math", "Science" };
[HttpGet]
[ODataRoute("GetPdf")]
public void DownloadPDF()
{
HttpContext.Current.Response.ContentType = "application/pdf";
HttpContext.Current.Response.AddHeader("content-disposition", "inline;filename=Example.pdf");
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
Document doc = new Document(iTextSharp.text.PageSize.A4, 10f, 10f, 100f, 0f);
string pdfFilePath = HttpContext.Current.Server.MapPath(".") + "/PDFFiles";
PdfWriter wri = PdfWriter.GetInstance(doc, HttpContext.Current.Response.OutputStream);
doc.Open();
doc.AddAuthor("Test author");
doc.AddCreationDate();
PdfContentByte cb = wri.DirectContent;
Font _bf = new Font(Font.FontFamily.HELVETICA, 6);
PdfFormField _radioGroup = PdfFormField.CreateRadioButton(wri, true);
_radioGroup.FieldName = "language_gc";
Rectangle _rect;
RadioCheckField _radioG;
PdfFormField _radioField1;
PdfFormField field;
for (int i = 0; i < LANGUAGES_gc.Length; i++)
{
_rect = new Rectangle(46, 806 - i * 40, 60, 788 - i * 40);
_radioG = new RadioCheckField(wri, _rect, null, LANGUAGES_gc[i]);
_radioG.BackgroundColor = new GrayColor(0.8f);
_radioG.BorderColor = GrayColor.BLACK;
_radioG.CheckType = RadioCheckField.TYPE_CIRCLE;
_radioField1 = _radioG.RadioField;
_radioGroup.AddKid(_radioField1);
ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT, new Phrase(LANGUAGES_gc[i], new Font(Font.FontFamily.HELVETICA, 18)), 70, 790 - i * 40, 0);
}
/* Button */
_rect = new Rectangle(300, 806, 370, 788);
PushbuttonField button = new PushbuttonField(wri, _rect, "Buttons");
button.BackgroundColor = new GrayColor(0.75f);
button.BorderColor = GrayColor.GRAYBLACK;
button.BorderWidth = 1;
button.BorderStyle = PdfBorderDictionary.STYLE_BEVELED;
button.TextColor = GrayColor.GRAYBLACK ;
button.FontSize = 12;
button.Text = "Submit";
//button.Layout = PushbuttonField.LAYOUT_ICON_LEFT_LABEL_RIGHT;
button.ScaleIcon = PushbuttonField.SCALE_ICON_ALWAYS;
button.ProportionalIcon = true;
button.IconHorizontalAdjustment = 0;
field = button.Field;
field.Action = PdfAction.JavaScript("this.showButtonState()", wri);
wri.AddAnnotation(field);
//}
//return ms.ToArray();
/*----------------------------------------------------*/
wri.AddAnnotation(_radioGroup);
wri.AddAnnotation(button.Field);
cb = wri.DirectContent;
doc.Close();
HttpContext.Current.Response.Write(doc);
HttpContext.Current.Response.End();
}
Can someone suggest me the solution??
Let's make an analogy here, with a simpler file-type. Suppose you're showing the user a textfile. They open it in their native .txt app (notepad) and make some changes.
Do you expect their changes to be communicated automatically back to your server?
Or that their changes are magically propagated? Of course not.
And even if it would, this seems like functionality notepad would have to provide, rather than something the creator of the file should do.
Now, as it so happens, there is a particular standard of pdf documents that exists for precisely your use-case. Essentially, the document sets up a connection to a server, and synchronizes. However, this standard is rather obscure, not a lot of viewers support it.
To the best of my knowledge, no pdf library (including iText) supports making documents like that.

zxing Datamatrix generator creating rectangular barcode which can't be scanned

I am using barcodewriter to write datamatrix barcoe. While most of the times it creates correct square style datamatrix barcode, for some of text it creates rectangular shaped barcode.
For inputData like below it creates rectangular barcode
8004600000070000017
C/TH PAUL PENGELLY
C/TH NICKY PARSONS
C/TH ROSEMARIE BARTOLOME
while for others it creates square styled: CTH HEKT-WOODROW MORGAN
800460000007
800460000007000001700000
i am usinf this code to generate code:
BarcodeWriter writer = new BarcodeWriter() { Format = BarcodeFormat.DATA_MATRIX };
var img = writer.Write(inputData);
return new Bitmap(img);
img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
dto.BarcodeImage = ms.ToArray();
How can I make sure that I always get Square shaped datamatrix?
I have alread tried adding height,width options.
Thanks
There is SymbolShape option which can be used to force shape .
DatamatrixEncodingOptions options = new DatamatrixEncodingOptions()
{
Height = 300,
Width = 300,
PureBarcode = true,
Margin = 1,
SymbolShape = SymbolShapeHint.FORCE_SQUARE
};
It is not easy to detect but after careful reviewing, I found how to do it.
readonly DataMatrixWriter DMencoder = new();
readonly Dictionary<EncodeHintType, object> DMencodeType = new()
{
[EncodeHintType.DATA_MATRIX_DEFAULT_ENCODATION] = Encodation.C40, //Optional
[EncodeHintType.DATA_MATRIX_SHAPE] = SymbolShapeHint.FORCE_SQUARE
};
DMencoder.encode(matrixText, BarcodeFormat.DATA_MATRIX, 100, 100, DMencodeType)

Trying to make use of Jcrop and serverside image resizing with scala Scrimage lib

I'm trying to combine jcrop and scrimage but I'm having trouble in understanding
the documentation of scrimage.
The user uploads an image. When the upload is done the user is able choose a fixed
area to crop with Jcrop:
upload.js
$(function () {
$('#fileupload').fileupload({
dataType: 'json',
progress: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$("#progress").find(".progress-bar").css(
"width",
progress + "%"
);
},
done: function (e, data) {
$("#cropArea").empty();
var cropWidth = 210;
var cropHeight = 144;
if(data.result.status == 200) {
var myImage = $("<img></img>", {
src: data.result.link
}).appendTo('#cropArea');
var c = myImage.Jcrop({
allowResize: false,
allowSelect: false,
setSelect:[0,0,cropWidth,cropHeight],
onSelect: showCoords
});
}
}
});
});
Example:
When the user is satisfied the coordinates will be posted to the server and there is where the magic should happen.
Controller:
def uploadFile = Action(multipartFormDataAsBytes) { request =>
val result = request.body.files.map {
case FilePart(key, filename, contentType, bytes) => {
val coords = request.body.dataParts.get("coords")
val bais = new ByteArrayInputStream(bytes)
Image(bais).resize(magic stuff with coords)
Ok("works")
}
}
result(0)
}
If i read the docs for scrimage and resize:
Resizes the canvas to the given dimensions. This does not scale the
image but simply changes the dimensions of the canvas on which the
image is sitting. Specifying a larger size will pad the image with a
background color and specifying a smaller size will crop the image.
This is the operation most people want when they think of crop.
But when trying to implement resize with an inputstream Image(is).resize() I'm not sure I how should do this. Resize takes a scaleFactor, position and color... I guess I should
populate the position with the coords I get from jcrop??, and what do I do with the scaleFactor? Anybody got a good example of how to do this this?
Thank you for two great libs!
Subimage is what you want. That lets you specify coordinates rather than offsets.
So simply,
val image = // original
val resized = image.subimage(x,y,w,h) // you'll get these from jcrop somehow

how to display two line charts on a graphview in android getting the values from database?

how to display two line charts on a graphview in android getting the values from database?
here is my code
gvp1=new GraphViewData[systolic.size()];
for(int i=0;i<gvp1.length;i++)
{
gvp1[i]=new GraphViewData(Double.parseDouble(systolic.get(i).toString()), Double.parseDouble(diastolic.get(i).toString()));
System.out.println("array avp1 is......."+Double.parseDouble(systolic.get(i).toString()));
}
LineGraphView graphView = new LineGraphView(
this
, "BP Graph"
);
graphView.addSeries(new GraphViewSeries(gvp1));
System.out.println("in graphview......"+gvp1);
/*
graphView.addSeries(new GraphViewSeries(new GraphViewData[] {
new GraphViewData(1, 2.0d)
}));*/
/*
ViewHolder v = null;
v = new ViewHolder();
convertView=null;
*/
setContentView(graphView);
// setContentView(R.layout.demo11);
ImageView iv = new ImageView(this);
iv.setImageResource(R.drawable.graph_header);
graphView.addView(iv);
}
this is how i am getting values from database to graph. but i want another line graph to be plotted on same scale.
any working code will be a great help..
Just call addSeries putting the other data of line graph.
See my implementation:
GraphViewSeries line1Series = new GraphViewSeries("LINE ONE", new GraphViewSeriesStyle(Color.GREEN, 3), new GraphViewData[] { new GraphViewData(0, 0) }); // put an complete array
GraphViewSeries line2Series = new GraphViewSeries("LINE TWO", new GraphViewSeriesStyle(Color.BLUE, 3), new GraphViewData[] { new GraphViewData(0, 0) }); // put an complete array
graphView = new LineGraphView(this, "Graph with 2 lines");
graphView.addSeries(line1Series);
graphView.addSeries(line2Series);
graphView.setShowLegend(true);
graphView.setLegendAlign(LegendAlign.TOP);
graphView.setGraphViewStyle(new GraphViewStyle(Color.DKGRAY, Color.DKGRAY, Color.LTGRAY));
graphView.redrawAll();
I hope this can help you.

Postprossing error - copyTexImage2D: framebuffer is incompatible format

Postprossing error - copyTexImage2D: framebuffer is incompatible format
I'm trying to use the post effects as presented in the samples, but I keep getting the following error in my console and nothing is rendering. Any ideas on what might be causing this? I don't think anything that matters is different than in the postprocessing example.
WebGL: INVALID_OPERATION: copyTexImage2D: framebuffer is incompatible format
renderer = new THREE.WebGLRenderer()
renderer.setSize(window.innerWidth, window.innerHeight)
renderer.setClearColorHex(0x000000, 1)
renderer.sortObjects = false;
...
composer = new THREE.EffectComposer( renderer )
composer.addPass( new THREE.RenderPass( scene, camera ) )
effect = new THREE.ShaderPass( THREE.DotScreenShader )
effect.uniforms[ 'scale' ].value = 4
composer.addPass( effect )
effect = new THREE.ShaderPass( THREE.FXAAShader )
composer.addPass( effect )
render = ->
requestAnimationFrame(render)
composer.render()
render()
You could try to add alpha to the WebGLRenderer default framebuffer using:
renderer = new THREE.WebGLRenderer( { antialias: true, alpha: true } );
I found out the error, there's a bug where EffectComposer is incompatable with LensFlare, submitting a change.
Basing on #Axiverse suggest, if your problem come with usage of lens flare (or maybe anything else...), simply add your own render target.
//...
var pixelRatio = renderer.getPixelRatio();
var width = Math.floor( renderer.context.canvas.width / pixelRatio ) || 1;
var height = Math.floor( renderer.context.canvas.height / pixelRatio ) || 1;
var renderTarget = new THREE.WebGLRenderTarget(width, height, {
minFilter: THREE.LinearFilter,
magFilter: THREE.LinearFilter,
format: THREE.RGBAFormat, // <-- The line that fix all for me
stencilBuffer: false
});
var effectComposer = new THREE.EffectComposer(webGLRenderer, renderTarget);