B4J Question save canvas in jpg

jota

Active Member
Licensed User
Longtime 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
 

jota

Active Member
Licensed User
Longtime 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
 
Upvote 0

Daestrum

Expert
Licensed User
Longtime 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));
 }
 
Upvote 0

Daestrum

Expert
Licensed User
Longtime User
Same place I got the code for the javascript file. :D
 
Upvote 0

almontgreen

Active Member
Licensed User
Longtime 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?
 
Upvote 0
Top