Skip to content

Commit 52e260f

Browse files
committed
handle hidpi with half size PNG
1 parent 8c0f770 commit 52e260f

File tree

2 files changed

+32
-2
lines changed

2 files changed

+32
-2
lines changed

src/inline.jl

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -88,14 +88,39 @@ function display(d::InlineDisplay, M::MIME, x)
8888
"data" => d)))
8989
end
9090

91+
92+
# look for a short sequence in an array
93+
function get_ind(sub_arr, arr)
94+
nsub = length(sub_arr)
95+
search_end = length(arr) - nsub + 1
96+
return findfirst(i -> all(sub_arr .== arr[i:i+nsub-1]) , 1:search_end)
97+
end
98+
99+
# get w, h from PNG base64
100+
function png_wh(img::String)
101+
decoded = base64decode(img[1:32]) # you need 13 + 8 bytes, this is a bit extra
102+
ihdr = get_ind(b"IHDR", decoded) + 4 # find the location of the header
103+
w, h = ntoh.(reinterpret(Int32, decoded[ihdr:ihdr+8-1])) # get the 8 bytes after
104+
return w, h
105+
end
106+
107+
const retina = Ref(false) # flag for setting retina-type images
108+
91109
# override display to send IPython a dictionary of all supported
92110
# output types, so that IPython can choose what to display.
93111
function display(d::InlineDisplay, x)
94112
undisplay(x) # dequeue previous redisplay(x)
113+
114+
meta = metadata(x)
115+
data = display_dict(x)
116+
if retina[] && "image/png" in keys(data) # if retina, apply metadata to halve sizes
117+
w, h = png_wh(data["image/png"])
118+
meta["image/png"] = Dict("width" => w/2, "height" => h/2)
119+
end
95120
send_ipython(publish[],
96121
msg_pub(execute_msg, "display_data",
97-
Dict("metadata" => metadata(x), # optional
98-
"data" => display_dict(x))))
122+
Dict("metadata" => meta, # optional
123+
"data" => data)))
99124
end
100125

101126
# we overload redisplay(d, x) to add x to a queue of objects to display,

test/inline.jl

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,4 +22,9 @@ import IJulia: InlineIOContext
2222

2323
Base.show(InlineIOContext(buf), MIME("text/plain"), data)
2424
@test String(take!(buf)) == "TestDataType: Jupyter: \"foo\""
25+
26+
# test that we can extract a PNG header
27+
@test png_wh(
28+
"iVBORw0KGgoAAAANSUhEUgAAAAUAAAAMCAYAAACqYHctAAAAE0lEQVR42mNk+P+/ngENMI4MQQCgfR3py/"
29+
* "xS9AAAAABJRU5ErkJggg==") == (5,12)
2530
end

0 commit comments

Comments
 (0)