djblue / portal

A clojure tool to navigate through your data.
https://djblue.github.io/portal/
MIT License
872 stars 81 forks source link

BufferedImage #213

Closed genmeblog closed 6 months ago

genmeblog commented 6 months ago

Is there a way to display JVM BufferedImage object?

djblue commented 6 months ago

@genmeblog, currently not directly. An easy work around would be to turn that object into a byte array then Portal should be able to render the image.

genmeblog commented 6 months ago

What should be a structure of such byte array? Encoded png or jpg?

djblue commented 6 months ago

I think either should work since I just pass the info directly to the web browser, but I've only tested png byte arrays.

genmeblog commented 6 months ago

Ok, thanks! Do you plan to add BufferedImage in the near future?

genmeblog commented 6 months ago

This works indeed:

(tap> (let [bufferedimage (java.awt.image.BufferedImage. 300 300 java.awt.image.BufferedImage/TYPE_INT_ARGB)
            baos (java.io.ByteArrayOutputStream.)]
        (javax.imageio.ImageIO/write bufferedimage "png" baos)
        (pview/image (.toByteArray baos))))
djblue commented 6 months ago

I think for now I would rather users go through datafy to achieve this, like:

(ns user
  (:require [clojure.core.protocols :refer [Datafiable]]
            [clojure.datafy :as d]
            [portal.api :as p]
            [portal.viewer :as v])
  (:import (java.awt.image BufferedImage ImageIO)
           (java.io ByteArrayOutputStream)))

(extend-protocol Datafiable
  BufferedImage
  (datafy [^BufferedImage bufferedimage]
    (let [baos (ByteArrayOutputStream.)]
      (ImageIO/write bufferedimage "png" baos)
      (v/image (.toByteArray baos)))))

(def submit (comp p/submit d/datafy))
(add-tap #'submit)
(tap> (BufferedImage. 300 300 BufferedImage/TYPE_INT_ARGB))

Additionally, the submit function doesn't need to use datafy for dispatch, it could use another method to determine how to transform tap>'d values.

djblue commented 6 months ago

Going to close this for now, feel free to open it back up if you have more questions.