blob: ffcac8b0bec91a79cd3a971e2e4a7b32f513a262 [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
15// +build ignore
16
17package main
18
19// draw-with-mask.go draws one image using a second image as an alpha mask
20// (scaled to the size fo the first image). The resultant image is PNG-encoded
21// to stdout.
22//
23// The result isn't necessarily beautiful, but it is an easy way to generate
24// test images containing an alpha channel.
25//
26// Usage: go run draw-with-mask.go color.png alpha.png > foo.png
27
28import (
29 "bufio"
30 "errors"
31 "image"
32 "image/png"
33 "os"
34
35 "golang.org/x/image/draw"
36
37 _ "image/gif"
38 _ "image/jpeg"
39)
40
41func main() {
42 if err := main1(); err != nil {
43 os.Stderr.WriteString(err.Error() + "\n")
44 os.Exit(1)
45 }
46}
47
48func main1() error {
49 if len(os.Args) != 3 {
50 return errors.New(`bad arguments: usage: "go draw-with-mask.go color.png alpha.png"`)
51 }
52 color, err := decode(os.Args[1])
53 if err != nil {
54 return err
55 }
56 alpha, err := decode(os.Args[2])
57 if err != nil {
58 return err
59 }
60 b := color.Bounds()
61 mask := makeMask(b, alpha)
62
63 dst := image.NewRGBA(b)
64 draw.DrawMask(dst, b, color, b.Min, mask, mask.Bounds().Min, draw.Src)
65
66 w := bufio.NewWriter(os.Stdout)
67 defer w.Flush()
68 return png.Encode(w, dst)
69}
70
71func decode(filename string) (image.Image, error) {
72 f, err := os.Open(filename)
73 if err != nil {
74 return nil, err
75 }
76 defer f.Close()
77 m, _, err := image.Decode(f)
78 return m, err
79}
80
81func makeMask(bounds image.Rectangle, src image.Image) *image.Alpha {
82 dst := image.NewGray(bounds)
83 draw.CatmullRom.Scale(dst, dst.Bounds(), src, src.Bounds(), draw.Src, nil)
84 return &image.Alpha{
85 Pix: dst.Pix,
86 Stride: dst.Stride,
87 Rect: dst.Rect,
88 }
89}