Download image and save as file

In case someone needs to download an image from a website (or camera) and save it as a file, I’ll post the below code as I was facing some obstacles (couldn’t get it done by sendHttpGetRequest, etc).
Obviously, you could use executeCommandline in combination with wget or curl, but I try to keep my scripts as platformindependent as possible, thus trying to avoid executeCommandline.
If someone has a different approach, I am happy if you post it here.

var url = "http://mycamera/record/current.jpg";
var path = "/etc/openhab/html/download";
var file = path + "/" + time.LocalDateTime.now() + ".jpg";
var HttpUtil = Java.type("org.openhab.core.io.net.http.HttpUtil");
var Files = Java.type("java.nio.file.Files");
var Paths = Java.type("java.nio.file.Paths");
var rawImage = HttpUtil.downloadImage(url, 4000);
if (rawImage !== null && rawImage !== undefined) {
  var byteArray = rawImage.getBytes();
  Files.write(Paths.get(file), byteArray);
}

I just use mqtt and send it to an image type item.

mosquitto_pub -h 192.168.1.164 -t raw/weatherimage -f "$outfile"

I have the image go to a oh-image-card and have my weather forecast there and I update the image every minute.


Its night here now so the image isn’t great. :grin:

Here is the yaml…

component: oh-image-card
config:
  action: popup
  actionModal: widget:BOM-widget-with-temps
  footer: ="Max " + JSON.parse(items.BOMdata.state).data[0].temp_max + "  "
    +     JSON.parse(items.BOMdata.state).data[0].extended_text + " "
    +     JSON.parse(items.BOMdata.state).data[0].rain.chance + "% chance of
    rain " +     JSON.parse(items.BOMdata.state).data[0].rain.amount.min + " to
    " +     JSON.parse(items.BOMdata.state).data[0].rain.amount.max + " mm."+ "
    Issued     at "
    +     dayjs(JSON.parse(items.BOMdata.state).metadata.issue_time).format('HH:mm')
  item: Rawmqttdata_Weathercamimage
  title: =dayjs(JSON.parse(items.BOMdata.state).data[0].date).format('dddd MMM  D')

With JRuby:

From URL directly to File

# frozen_string_literal: true

require "open-uri"

url = "http://mycamera/record/current.jpg"
filename = OpenHAB::Core.config_folder / "html/download" / Time.now.strftime("%Y-%m-%d_%H:%M:%S.jpg")
URI.parse(url).open{ |f| File.write(filename, f.read) }

From URL to an ImageItem:

MyImageItem.update_from_url("http://mycamera/record/current.jpg")

From ImageItem to File

e.g. when the image is linked to an mqtt channel that updates the image data

filename = OpenHAB::Core.config_folder / "html/download" / Time.now.strftime("%Y-%m-%d_%H:%M:%S.jpg")
File.write(filename, MyImageItem.state.bytes)

It is frustrating how easy it is with jruby😂
One day, I‘ll switch to jruby.

Oops that extra read was redundant. It should be:

URI.parse(url).open { |f| File.write(filename, f.read) }

This barely scratches the surface!

You’ll be kicking yourself for not trying it out sooner.