Search code examples
goimagickgo-imagick

Create a function with return type of image magick object in go lang


I want to create image magick object corresponding to images stroed in S3. So, i was writing a function which will take necessary arguments and return the image magick object. But, no luck with it. This is the Imagick Library which i am using.

     func main() {
        mw := imagick.NewMagickWand()
        defer mw.Destroy()
        mw = ObjImagick(bucketName, keyName, region)
    }



  func ObjImagick(bktName string, kName string, region string) ( ) {

    s3Client := s3.New(session.New(), &aws.Config{Region: aws.String(region)})
        params := &s3.GetObjectInput{
        Bucket: aws.String(bktName),
        Key: aws.String(kName),
        }

    out, err := s3Client.GetObject(params)
    if err != nil {
        log.Fatal(err)
    }

    img, err := ioutil.ReadAll(out.Body)
    if err != nil {
        log.Fatal(err)
    }      

    mw := imagick.NewMagickWand()
    defer mw.Destroy()

    err = mw.ReadImageBlob(img)
    if err != nil {
        log.Fatal(err)
    }

       return mw
}

Solution

  • Well, NewMagickWand() returns a *MagickWand, so you can create your function like:

    func ObjImagick(bktName string, kName string, region string) *imagick.MagickWand {
        .......................
        mw := imagick.NewMagickWand()
        // defer mw.Destroy() this destroys the wand when ObjMagick returns.
        // so you can't do this here, your func caller needs to handle destroying the object.
    
        err = mw.ReadImageBlob(img)
        if err != nil {
            log.Fatal(err)
        }
    
        return mw
    }
    

    Then the caller has to call .Destroy(), for example:

    func main() {
        mw := ObjImagick(bucketName, keyName, region)
        defer mw.Destroy()
    }