github.com/bazelbuild/rules_webtesting@v0.2.0/go/cropper/cropper.go (about)

     1  // Copyright 2016 Google Inc.
     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  //      http://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  // Package cropper provides an image cropping function.
    16  package cropper
    17  
    18  import (
    19  	"errors"
    20  	"image"
    21  	"image/draw"
    22  )
    23  
    24  type subImageSupported interface {
    25  	SubImage(r image.Rectangle) image.Image
    26  }
    27  
    28  // Crop crops an image to bounds.
    29  // The cropped image may be a view on the original image or a completely distinct image.
    30  func Crop(src image.Image, bounds image.Rectangle) (image.Image, error) {
    31  	s, ok := src.(subImageSupported)
    32  	if !ok {
    33  		return nil, errors.New("crop only works with images that support subimage")
    34  	}
    35  
    36  	return s.SubImage(bounds), nil
    37  }
    38  
    39  // Blackout replaces a given rectangle in the image with a black rectangle.
    40  // The function may modify the original image.
    41  func Blackout(src image.Image, bounds image.Rectangle) (image.Image, error) {
    42  	s, ok := src.(draw.Image)
    43  	if !ok {
    44  		return nil, errors.New("crop only works with images that implement draw.Image")
    45  	}
    46  
    47  	draw.Draw(s, bounds, image.Black, image.ZP, draw.Src)
    48  	return s, nil
    49  }