I use the JXL API to add an Image to an Excel file. Libraries used:
jcommon (1.0.14)
jfreechart (1.0.13)
jxl (2.6.10)
// chartImage is of type BufferedImage
com.KeyPoint.PngEncoder encoder = new com.KeyPoint.PngEncoder(chartImage, true, 0, 0);
jxl.write.WritableImage image = new jxl.write.WritableImage(0, 2, (chartImage.getWidth()/100),16,
encoder.pngEncode());
sheet.addImage(image);
The problem is that the WritableImage constructors take widths and heights in terms of rows and columns (width: column 0 to column chartImage.getWidth()/100, height: row 2 to row 16). This causes the chart image to blur.
How do I get the original image into the Excel using JXL? Kindly help. Thanks! :-)
The issue lies with either the compression used in Excel or the encoder you used.
A solution that works is drawing the chart larger than the intended image, and then letting Excel do the down-scaling. This ensures clarity although a chart-filled workbook will be much larger than before.
AFAIK that is the only solution to the problem. I have had similar issues with Word and PowerPoint, and the solution seems to be upscaling.
When you scale the chart you should note that the font sizes need to be changed too.
Don't use PngEncoder directly. Instead, use the relevant ChartUtilities method, which will find the Sun/Oracle PNG encoder if available.
Related
I'm evaluating Direct2D for research purposes, and while I was at it, I decided to render my usual help text with a DirectWrite custom text renderer, which converts the text to a path geometry in order to add outline (as demonstrated in the DWriteHelloWorld sample on MSDN).
However, some letters have weird "hairs" or "horns" on them (picture: stroke width of 3 and 5).
Also tried with other fonts (f.e. Consolas), the effect is the same.
Source code (VS 2015):
https://www.dropbox.com/s/v3204h0ww2cp0yk/FOR_STACKOVERFLOW_12.zip?dl=0
The solution is as easy as I hoped. The "hairs" are actually caused by the line joints which D2D generates. Therefore the solution is to create an ID2D1StrokeStyle object as the following:
ID2D1StrokeStyle* strokestyle = nullptr;
D2D1_STROKE_STYLE_PROPERTIES strokeprops = D2D1::StrokeStyleProperties();
strokeprops.lineJoin = D2D1_LINE_JOIN_ROUND;
d2dfactory->CreateStrokeStyle(strokeprops, NULL, 0, &strokestyle);
// draw
rendertarget->DrawGeometry(transformedgeometry, blackbrush, 3.0f, strokestyle);
With this solution, the text is rendered as expected (perhaps a little more roundish at the joints).
I would suspect the reason for that is that default flattening tolerance in D2D does not work well for the purpose of rendering glyph outlines, at small enough sizes. Normally you'd use bitmap rendering for small sizes and outlines for larger ones, according to GetRecommendedRenderingMode(). Do you have same artifacts if you increase font size let's say 10 times?
I'm currently working on a little game written in JS using Pixi.js(https://github.com/pixijs). One Problem has occured currently, I'm trying to implement pixel exact collision between shapes, while I was programing a little I noticed that all the pixel RBGA values of my images are just 0.
I searched on the web but for a while but the only reason for those Problems I could find was that the canvas was tainted because of CORS(Pixel RGB values are all zero).
But this can't be the reason in my case because I created the sprites myself, I'm not loading them from other (any) domains or something like that.
Could this be a problem with the images? How do I avoid that? I will append some code that works if I use other images (some images I downloaded for tests).
const app = new PIXI.Application({width: 500, height: 500});
document.body.appendChild(app.view);
PIXI.loader.add("sprites/test.png")
.load(() => {
let img = new PIXI.Sprite(PIXI.loader.resources["sprites/test.png"].texture);
app.stage.addChild(img);
console.log(app.renderer.extract.pixels(img));
});
Edit: I tried getting the RGBA values using a short Java Program btw, same problem. Every single value is zero.
I have no prior iText 5 experience but only started reading about iText 7 less than one month ago. I have a fairly complicated task of converting JPanel displays within a master JTabbedPane into pdf with several simultaneous requirements. I use Swing to specify font and need to embed the font in the pdf. I need to specify asymmetric pdf margins and distribute top versus bottom, as well as left versus right margins evenly that each JPanel dynamically left open on a landscape US paper. My generic Java program uses per pixel x and y positioning of all JComponents and the program dynamically knows the x and y extent of each completed JPanel display depending on data content of multiple stacked JTables on each JPanel. Using 100 pixels per inch, my JPanels will not need scaling to fit the landscape US letter size paper using my specified margins.
I made three separate searches on developers.itextpdf.com with queries of "export JTable to pdf", "export JPanel to pdf", and "export JFrame to pdf" but found no results whether I filter with iText 5 or 7. The same queries typed into the general internet browser search box turned up multiple results from Stack Overflow (such as How2: Add a JPanel to a Document then export to PDF) and miscellaneous sources. However, all the solutions are iText 5 dependent because they all use PdfTemplate and PdfContentByte which are absent from iText 7, and a different version of PdfWriter with getInstance method. However, iText7 export JPanel to pdf shows no result on Stackoverflow. Since I started after iText 7 has been introduced, I prefer to code my JPanel to pdf conversion with iText 7 if someone can point me how to do it.
Even with the iText 5 solution, how can I be sure that my single Java font specified in my JComponents get transferred into the intermediate Graphics2D (if iText 7 also uses it) and properly linked up with an iText font embedding call. Additional things I have to tinker with are converting 100 pixels per inch in JPanel to 72 pts per inch on pdf, and the placement of pdf media box for proper margins. I hope simple mathematics with some special rounding attentions are all that's needed for the tinkering part. Please allow me to thank in advance for any forth coming help.
I had a similar problem, but went for a much simpler solution. It is very easy to convert a Swing component into a Java Image, in much the same way you would take a screenshot of the running app. Once you have a big BufferedImage containing your JPanel contents, you can write it straight into a PDF Document. Then you don't need to mimic any of the Swing code being used to populate the JTabbedPane at all.
Here are some code fragments to help you out. Suppose your app creates a JPanel containing Swing elements like JLabel's and the like. To capture this as a Java image, you could do:
JPanel myPan = createPanelForTab1(); << your main app code does this
// Take a snapshot of myPan as a Java image
BufferedImg jImg = new BufferedImmage(myPan.getWidth(),
myPan.getHeight(),
BufferedImage.TYPE_INT_ARGB);
myPan.paint(jImg.createGraphics());
Then convert the Java Image to an iText Image (they are different things). You might also want to scale this image down a bit to fit on a page:
itextpdf.layout.element.Image itextImg = new Image(
ImageDataFactory.create(jImg, null));
itextImg.scaleToFit(400.0f, 9999.9f); // (if it's too big)
Adding this img to a PDF Document is as simple as:
itextImg.setHorizontalAlignment(HorizontalAlignment.CENTER);
document.add(new Paragraph(iTextImg));
Perhaps this is the way to go?
(Note: Since you are taking a screenshot, you don't need to worry about any font requirements in the PDF. On the downside, though, there is no text from the Java app in the PDF so you can't search it, for example.)
I'm having an issue with attempting to save some plots with transparent ellipsoids on them if I attempt to save them with .ps/.eps extensions.
Here's the plot saved as a .png:
If I choose to save it as a .ps/.eps here is what it looks like:
How I got around this, was to use ImageMagick to convert the original png to a ps. The only problem is that the image in png format is about 90k, and it becomes just under 4M after conversion. This is not good since I have a lot of these images, and it will take too much time to compile my latex document. Does anyone have a solution to this?
The problem is that eps does not support transparencies natively.
There are few options:
rasterize the image and embed in a eps file (like #Molly suggests) or exporting to pdf and converting with some external tool (like gs) (which usually relies as well on rasterization)
'mimic' transparency, giving a colour that looks like the transparent one on a given background.
I discussed this for sure once on the matplotlib mailing list, and I got the suggestion to rasterize, which is not feasible as you get either pixellized or huge figures. And they don't scale very nicely when put into, e.g., a publication.
I personally use the second approach, and although not ideal, I found it good enough. I wrote a small python script that implements the algorithm from this SO post to obtain a solid RGB representation of a colour with a give transparency
EDIT
In the specific case of your plot try to use the zorder keyword to order the parts plotted. Try to use zorder=10 for the blue ellipse, zorder=11 for the green and zorder=12 for the hexbins.
This way the blue should be below everything, then the green ellipse and finally the hexbins. And the plot should be readable also with solid colors. And if you like the shades of blue and green that you have in png, you can try to play with mimic_alpha.py.
EDIT 2
If you are 100% sure that you have to use eps, there are a couple of workarounds that come to my mind (and that are definitely uglier than your plot):
Just draw the ellipse borders on top of the hexbins.
Get centre and amplitude of each hexagon, (possibly discard all zero bins) and make a scatter plot using the same colour map as in hexbin and adjusting the marker size and shape as you like. You might want to redraw the ellipses borders on top of that
Another alternative would be to save them to pdf
savefig('myfigure.pdf')
That works with pdflatex, if that was the reason why you needed to use eps and not svg.
You can rasterize the figure before saving it to preserve transparency in the eps file:
ax.set_rasterized(True)
plt.savefig('rasterized_fig.eps')
I had the same problem. To avoid rasterizing, you can save the image as a pdf and then run (on unixish systems at least) in a terminal:
pdftops -eps my.pdf my.eps
Which gives a .eps file as output.
I solved this by:
1) adding a set_rasterization_zorder(1) when defining the figure area:
fxsize=16
fysize=8
f = figure(num=None, figsize=(fxsize, fysize), dpi=180, facecolor='w',
edgecolor='k')
plt.subplots_adjust(
left = (18/25.4)/fxsize,
bottom = (13/25.4)/fysize,
right = 1 - (8/25.4)/fxsize,
top = 1 - (8/25.4)/fysize)
subplots_adjust(hspace=0,wspace=0.1)
#f.suptitle('An overall title', size=20)
gs0 = gridspec.GridSpec(1, 2)
gs11 = gridspec.GridSpecFromSubplotSpec(1, 1, subplot_spec=gs0[0])
ax110 = plt.Subplot(f, gs11[0,0])
f.add_subplot(ax110)
ax110.set_rasterization_zorder(1)
2) a zorder=0 in each alpha=anynumber in the plot:
ax110.scatter(xs1,ys1 , marker='o', color='gray' , s=1.5,zorder=0,alpha=0.3)#, label=label_bg)
and
3) finally a rasterized=True when saving:
P.savefig(str(PLOTFILENAME)+'.eps', rasterized=True)
Note that this may not work as expected with the transparent keyword to savefig because an RGBA colour with alpha<1 on transparent background will be rendered the same as the RGB colour with alpha=1.
As mentioned above, the best and easiest choice (if you do not want to loose resolution) is to rasterized the figure
f = plt.figure()
f.set_rasterized(True)
ax = f.add_subplot(111)
ax.set_rasterized(True)
f.savefig('figure_name.eps',rasterized=True,dpi=300)
This way, you can manage the size by dpi option as well. In fact, you can also play with the zorder below you want to apply the rasterization:
ax.set_rasterization_zorder(0)
Note: It is important to keep f.set_rasterized(True) when you use plt.subplot and plt.subplot2grid functions. Otherwise, label and tick area will not appear in the .eps file
My solution is to export the plot as .eps, load it up to Inkscape for example, then Ungroup the plot, select the object that I want to set the transparency and just edit the Opacity of the Fill in the "Fill and Stroke" tab.
You can save the file as .svg if you want to tweak it later, or export the image for a publication.
If you are writing the academic paper in latex, I would recommend you export the .pdf file rather than .eps. The .pdf format supports transparency perfectly and has good compression efficiency, and most importantly, can be easily edited in Adobe Illustrator.
If you wanna further edit the graph (NOT EDITING DATA! I MEAN, FOR GOOD-LOOKING), you could open the exported graph, in Adobe Acrobat - Edit - Copy elements into Adobe Illustrator. The two software can handle everything perfectly.
I work happily with this method. Everything clear, editable and small-size. Hope can help.
I am trying to modify the default I-beam cursor image. I'm using [[[NSCursor IBeamCursor] image] representations], passing each one through a CIFilter and adding it to a new image. However, the resulting cursor looks as though it is rendering the low-resolution images.
The High Resolution Guidelines say:
For custom cursors, you can pass a multirepresentation TIFF to the NSCursor class method initWithImage:hotSpot:.
So I would expect this to work. Additionally, if I get the -TIFFRepresentation of the original image and my modified image, and write them to disk, they both look like multi-page TIFF files with the same size images. What could I be doing wrong?
I have a somewhat-temporary solution: manually call -setSize: on each image representation, dividing the pixel height and width by the screen's scale factor. However, this technique doesn't seem like it will work ideally with multiple screens.
You're right on. I've been debugging this all day and I'm pretty sure I've got it nailed. I'm not doing exactly the same thing you are (my images are loaded from a file) but the end result is exactly the same.
The trick is to set the first representation of the multi-representation image to the non-retina size. If you are loading your cursors from an image file, you must take this extra step to adjust the size of the representations to match. It doesn't work 'out-of-the-box' as you would expect.
I've tested this on a machine with two monitors and dragging the window from the retina display to the non-retina display acts as it should, displaying the high/low resolution images for the cursor.
I had a similar problem a while ago: I had my cursor in a PDF, and it always drew as if it was a pixel image at 1:1 size, blown up. There's a solution to that in NSCursor: Using high-resolution cursors with cursor zoom (or retina).
Maybe someone can use that technique to solve this problem? My guess is creating an image with the same size but a different CTM marks it as the same size but Retina. What #jtbrandes is doing probably marks it as a different size and non-Retina. So you're effectively losing the scale factor information. If you create an image with a CTM in the hints, maybe you can draw the filtered images into it and it'll be detected right.