grph-bmp.lua /size: 2340 b    last modification: 2021-10-28 13:50
1if not modules then modules = { } end modules ['grph-bmp'] = {
2    version   = 1.001,
3    comment   = "companion to grph-inc.mkiv",
4    author    = "Hans Hagen, PRAGMA-ADE, Hasselt NL",
5    copyright = "PRAGMA ADE / ConTeXt Development Team",
6    license   = "see context related readme files"
7}
8
9local random        = math.random
10local context       = context
11
12local report_bitmap = logs.reporter("graphics","bitmap")
13
14local bitmaps       = { }
15graphics.bitmaps    = bitmaps
16
17local wrapimage     = images.wrap
18
19function bitmaps.new(xsize,ysize,colorspace,colordepth,mask,index)
20    if not xsize or not ysize or xsize == 0 or ysize == 0 then
21        report_bitmap("provide 'xsize' and 'ysize' larger than zero")
22        return
23    end
24    if not colorspace then
25        report_bitmap("provide 'colorspace' (1, 2, 3, 'gray', 'rgb', 'cmyk'")
26        return
27    end
28    if not colordepth then
29        report_bitmap("provide 'colordepth' (1, 2)")
30        return
31    end
32    return graphics.identifiers.bitmap {
33        colorspace = colorspace,
34        colordepth = colordepth,
35        xsize      = xsize,
36        ysize      = ysize,
37        mask       = mask and true or nil,
38        index      = index and true or nil,
39    }
40end
41
42local function flush(bitmap)
43    local specification = backends.codeinjections.bitmap(bitmap)
44    if specification then
45        return wrapimage(specification)
46    end
47end
48
49bitmaps.flush = flush
50
51function bitmaps.tocontext(bitmap,width,height)
52    local bmp = flush(bitmap)
53    if bmp then
54        if type(width) == "number" then
55            width = width .. "sp"
56        end
57        if type(height) == "number" then
58            height = height .. "sp"
59        end
60        if width or height then
61            context.scale (
62                {
63                    width  = width,
64                    height = height,
65                },
66                bmp
67            )
68        else
69            context(bmp)
70        end
71    end
72end
73
74local function placeholder(nx,ny)
75
76    local nx     = nx or 8
77    local ny     = ny or nx
78    local bitmap = bitmaps.new(nx,ny,"gray",1)
79    local data   = bitmap.data
80
81    for i=1,ny do
82        local d = data[i]
83        for j=1,nx do
84            d[j] = random(100,199)
85        end
86    end
87
88    return backends.codeinjections.bitmap(bitmap)
89
90end
91
92bitmaps.placeholder = placeholder
93