B4J Question save canvas in jpg

jota

Active Member
Licensed User
Hi I'm using this code to save the image of a canvas.

Dim out As OutputStream = File.OpenOutput(rutaDestio, fichero, False)
c.Snapshot.WriteToStream(out)
out.Close
It works well but I need to be in JPG format, how I can get it?

Thank you
 

Erel

Administrator
Staff member
Licensed User
There is no simple way to change the file format. The reason that JPG was not added is that there were all kinds of color issues with the JPEG encoder.
 

jota

Active Member
Licensed User
And some way to modify the quality of PNG? I'm converting images and putting watermark and the end result gives me 350kb files and was expected to work on 110kb. Thank you
 

Erel

Administrator
Staff member
Licensed User
PNG is a lossless format. You cannot control its compression level.
 

Daestrum

Well-Known Member
Licensed User
There is a way, not elegant and requires java 8 and the jNashorn library.
B4X:
Sub Process_Globals
    Private fx As JFX
    Private MainForm As Form
    Private label1 As Label
    Private nashorn As jNashorn
End Sub

Sub AppStart (Form1 As Form, Args() As String)
    MainForm = Form1
    MainForm.RootPane.LoadLayout("labelstest") 'contains just a label 'label1'
    MainForm.Show
    label1.Text = "Hello"
    Dim out1 As OutputStream = File.OpenOutput("c:/temp/","img.png",False) 'temp file for png
    Dim out As InputStream = File.OpenInput("c:/temp/","img.png")
    label1.Snapshot.WriteToStream(out1) ' create snapshot of node
    Dim js As String = "x:/buffImage.js" ' path to where you put the buffImage.js file
    nashorn.evalFile(js) ' load the javascript file
    nashorn.enginePut("out",out) ' set var 'out' to inputstream
    nashorn.evalString("start(out ,""c:/temp/img.jpg"");") ' inputstream , output file name
End Sub
The required javascript file (buffImage.js) to convert from png to jpg

B4X:
var bufferedImage = Java.type("java.awt.image.BufferedImage");

function start(source,dest){ 
     bufferedImage = javax.imageio.ImageIO.read(source);
     var newBufferedImage = new java.awt.image.BufferedImage(bufferedImage.getWidth(),
            bufferedImage.getHeight(), java.awt.image.BufferedImage.TYPE_INT_RGB);
            // Color.WHITE is the background colour of the jpg image no transparency in jpg
     newBufferedImage.createGraphics().drawImage(bufferedImage, 0, 0, java.awt.Color.WHITE, null);
     javax.imageio.ImageIO.write(newBufferedImage, "jpg", new java.io.File(dest));
 }
 

almontgreen

Active Member
Licensed User
Thank you very much for the help, I chose to make a small library with the code in this link The adjoint if it helps someone. Thank you
Do you have an example for usage for pngTojpg library? I could really use!!! Thx! Also, does it require java8?
 
Top