blob: dfff8b6aa8fcc39851096ea8a7ece553b793cda9 [file] [log] [blame]
Nigel Tao621bd952020-01-24 10:01:43 +11001// Copyright 2020 The Wuffs Authors.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Nigel Tao788479d2021-08-22 10:52:51 +100015//go:build ignore
Nigel Tao621bd952020-01-24 10:01:43 +110016// +build ignore
17
18package main
19
20// draw-with-mask.go draws one image using a second image as an alpha mask
21// (scaled to the size fo the first image). The resultant image is PNG-encoded
22// to stdout.
23//
24// The result isn't necessarily beautiful, but it is an easy way to generate
25// test images containing an alpha channel.
26//
27// Usage: go run draw-with-mask.go color.png alpha.png > foo.png
28
29import (
30 "bufio"
31 "errors"
32 "image"
33 "image/png"
34 "os"
35
36 "golang.org/x/image/draw"
37
38 _ "image/gif"
39 _ "image/jpeg"
40)
41
42func main() {
43 if err := main1(); err != nil {
44 os.Stderr.WriteString(err.Error() + "\n")
45 os.Exit(1)
46 }
47}
48
49func main1() error {
50 if len(os.Args) != 3 {
51 return errors.New(`bad arguments: usage: "go draw-with-mask.go color.png alpha.png"`)
52 }
53 color, err := decode(os.Args[1])
54 if err != nil {
55 return err
56 }
57 alpha, err := decode(os.Args[2])
58 if err != nil {
59 return err
60 }
61 b := color.Bounds()
62 mask := makeMask(b, alpha)
63
64 dst := image.NewRGBA(b)
65 draw.DrawMask(dst, b, color, b.Min, mask, mask.Bounds().Min, draw.Src)
66
67 w := bufio.NewWriter(os.Stdout)
68 defer w.Flush()
69 return png.Encode(w, dst)
70}
71
72func decode(filename string) (image.Image, error) {
73 f, err := os.Open(filename)
74 if err != nil {
75 return nil, err
76 }
77 defer f.Close()
78 m, _, err := image.Decode(f)
79 return m, err
80}
81
82func makeMask(bounds image.Rectangle, src image.Image) *image.Alpha {
83 dst := image.NewGray(bounds)
84 draw.CatmullRom.Scale(dst, dst.Bounds(), src, src.Bounds(), draw.Src, nil)
85 return &image.Alpha{
86 Pix: dst.Pix,
87 Stride: dst.Stride,
88 Rect: dst.Rect,
89 }
90}