Fetching images from URIs

Started by Thomas Rohde, March 06, 2023, 05:45:04 AM

Previous topic - Next topic

Thomas Rohde

I was wondering whether someone has created a script to fetch an image from a URI, save to a temporary file, and then use createImage() and image property to set the image of an object?

Currently, createImage() only works with file paths.

merty

Sure, you have to mix Java and Javascript though.

This example fetches an image from URL and saves it in temporary directory with uniq id and same extension.
Use that to use call createImage() or whatever and when your finished, temporary file can be deleted

Be aware that there it is just an example, there isn't any errorhandling whatsoever in this code,


/* java imports */
const URL = Java.type('java.net.URL')
const FileOutputStream = Java.type('java.io.FileOutputStream')
const File = Java.type('java.io.File')
const ByteArray = Java.type("byte[]")

function URL2File(url) {
    UrlObj=new URL(url)
    stream=UrlObj.openStream()
    extension='.'+url.split('.').pop()
    tempfile=File.createTempFile("archi",extension,null)
    out = new FileOutputStream(tempfile)
    var buf=new ByteArray(1024)
    do {
        c=stream.read(buf,0,1024)
        if (c>0) out.write(buf,0,c)
    } while (c>0)
    out.close()
    return tempfile
}


console.clear()
tmp=URL2File("https://www.archimatetool.com/wp-content/uploads/2018/07/header.png")
console.log("file is:",tempfile.toString())

/* do your thing */

tempfile.delete()