MCPcopy
hub / github.com/willnorris/imageproxy / Transform

Function Transform

transform.go:41–129  ·  view source on GitHub ↗

Transform the provided image. img should contain the raw bytes of an encoded image in one of the supported formats (gif, jpeg, or png). The bytes of a similarly encoded image is returned.

(img []byte, opt Options)

Source from the content-addressed store, hash-verified

39// encoded image in one of the supported formats (gif, jpeg, or png). The
40// bytes of a similarly encoded image is returned.
41func Transform(img []byte, opt Options) ([]byte, error) {
42 if !opt.transform() {
43 // bail if no transformation was requested
44 return img, nil
45 }
46
47 // decode image metadata
48 cfg, _, err := image.DecodeConfig(bytes.NewReader(img))
49 if err != nil {
50 return nil, err
51 }
52
53 // prevent pixel flooding attacks
54 // accept no larger than a 100 megapixel image.
55 const maxPixels = 100_000_000
56 if cfg.Width*cfg.Height > maxPixels {
57 return nil, errors.New("image too large")
58 }
59
60 // decode image
61 m, format, err := image.Decode(bytes.NewReader(img))
62 if err != nil {
63 return nil, err
64 }
65
66 // apply EXIF orientation for jpeg and tiff source images. Read at most
67 // up to maxExifSize looking for EXIF tags.
68 if format == "jpeg" || format == "tiff" {
69 r := io.LimitReader(bytes.NewReader(img), maxExifSize)
70 if exifOpt := exifOrientation(r); exifOpt.transform() {
71 m = transformImage(m, exifOpt)
72 }
73 }
74
75 // encode webp and tiff as jpeg by default
76 if format == "tiff" || format == "webp" {
77 format = "jpeg"
78 }
79
80 if opt.Format != "" {
81 format = opt.Format
82 }
83
84 // transform and encode image
85 buf := new(bytes.Buffer)
86 switch format {
87 case "bmp":
88 m = transformImage(m, opt)
89 err = bmp.Encode(buf, m)
90 if err != nil {
91 return nil, err
92 }
93 case "gif":
94 fn := func(img image.Image) image.Image {
95 return transformImage(img, opt)
96 }
97 err = gifresize.Process(buf, bytes.NewReader(img), fn)
98 if err != nil {

Callers 6

TestTransformFunction · 0.85
TestTransform_EXIFFunction · 0.85
RoundTripMethod · 0.85

Calls 3

exifOrientationFunction · 0.85
transformImageFunction · 0.85
transformMethod · 0.80

Tested by 5

TestTransformFunction · 0.68
TestTransform_EXIFFunction · 0.68