Archi Forum

Archi Plug-ins => jArchi => Topic started by: Thomas Rohde on March 06, 2023, 05:45:04 AM

Title: Fetching images from URIs
Post by: Thomas Rohde on March 06, 2023, 05:45:04 AM
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.
Title: Re: Fetching images from URIs
Post by: merty on March 13, 2023, 20:10:00 PM
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()