All Products
Search
Document Center

Object Storage Service:IMG by using OSS SDK for Go

Last Updated:Feb 05, 2024

Image processing (IMG) is a secure, cost-effective, and highly reliable image processing service that is provided by Object Storage Service (OSS) to help you process images. After you upload source images to OSS, you can call RESTful API operations to process the images anytime, anywhere, and on any connected devices.

Usage notes

  • In this topic, the public endpoint of the China (Hangzhou) region is used. If you want to access OSS from other Alibaba Cloud services in the same region as OSS, use an internal endpoint. For more information about OSS regions and endpoints, see Regions and endpoints.

  • In this topic, access credentials are obtained from environment variables. For more information about how to configure access credentials, see Configure access credentials.

  • In this topic, an OSSClient instance is created by using an OSS endpoint. If you want to create an OSSClient instance by using custom domain names or Security Token Service (STS), see Initialization.

Use IMG parameters to process images

  • Use a single IMG parameter to process an image and save the processed image to your local computer

    package main
    
    import (
        "fmt"
        "os"
        "github.com/aliyun/aliyun-oss-go-sdk/oss"
    )
    
    func HandleError(err error) {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }
    
    func main() {
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
        provider, err := oss.NewEnvironmentVariableCredentialsProvider()
        if err != nil {
            fmt.Println("Error:", err)
            os.Exit(-1)
        }
    
        // Create an OSSClient instance. 
        // Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
        client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider))
        if err != nil {
        HandleError(err)
        }
    
        // Specify the name of the bucket in which the source image is stored. Example: examplebucket. 
        bucketName := "examplebucket"
        bucket, err := client.Bucket(bucketName)
        if err != nil {
        HandleError(err)
        }
    
        // Specify the name of the source image. If the image is not stored in the root directory of the bucket, you must specify the full path of the image. Example: example/example.jpg. 
        sourceImageName := "yourObjectName"
        // Specify the name of the processed image. 
        targetImageName := "LocalFileName"
        // Resize the image to 100 × 100 pixels and save the image to your local computer. 
        style := "image/resize,m_fixed,w_100,h_100"
        err = bucket.GetObjectToFile(sourceImageName, targetImageName, oss.Process(style))
        if err != nil {
        HandleError(err)
        }
    }
  • Use multiple IMG parameters to process an image and save the image to your local computer

    The following sample code provides an example on how to use multiple IMG parameters to process an image. The IMG parameters are separated by forward slashes (/).

    package main
    
    import (
        "fmt"
        "os"
        "github.com/aliyun/aliyun-oss-go-sdk/oss"
    )
    
    func HandleError(err error) {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }
    
    func main() {
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
        provider, err := oss.NewEnvironmentVariableCredentialsProvider()
        if err != nil {
            fmt.Println("Error:", err)
            os.Exit(-1)
        }
    
        // Create an OSSClient instance. 
        // Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
        client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider))
        if err != nil {
        HandleError(err)
        }
    
        // Specify the name of the bucket in which the source image is stored. Example: examplebucket. 
        bucketName := "examplebucket"
        bucket, err := client.Bucket(bucketName)
        if err != nil {
        HandleError(err)
         }
    
        // Specify the name of the source image. If the source image is not stored in the root directory of the bucket, you must specify the path of the image. Example: example/example.jpg. 
        sourceImageName := "exampledir/example.jpg"
        // Specify the name of the processed image. 
        targetImageName := "exampledir/newexample.jpg"
        // Resize the image to 100 × 100 pixels, rotate the image 90 degrees, and then save the image to your local computer. 
        style := "image/resize,m_fixed,w_100,h_100/rotate,90"
        err = bucket.GetObjectToFile(sourceImageName, targetImageName, oss.Process(style))
        if err != nil {
         HandleError(err)
        }
    }

Use an image style to process images

You can encapsulate multiple IMG parameters within a style and then use the style to process an image. For more information, see Image styles. The following sample code provides an example on how to use an image style to process an image:

package main

import (
	"fmt"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"os"
)

func HandleError(err error) {
	fmt.Println("Error:", err)
	os.Exit(-1)
}

func main() {
	// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
	// Create an OSSClient instance. 
	// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider))
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}

	// Specify the name of the bucket in which the source image is stored. Example: examplebucket. 
	bucketName := "examplebucket"
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		HandleError(err)
	}
	// Specify the name of the source image. If the source image is not stored in the root directory of the bucket, you must specify the full path of the image. Example: example/example.jpg. 
	sourceImageName := "example/example.jpg"
	// Save the processed image as newexample.jpg to your local computer. 
	targetImageName := "D:\\localpath\\newexample.jpg"
	// Use an image style to process the image. Set yourCustomStyleName to the name of the image style that you created in the OSS console. 
	style := "style/yourCustomStyleName"
	// Save the processed image to your local computer. 
	err = bucket.GetObjectToFile(sourceImageName, targetImageName, oss.Process(style))
	if err != nil {
		HandleError(err)
	}
}

Save processed images

You can call the ImgSaveAs operation to save processed images to a specific bucket.

package main

import (
    "encoding/base64"
    "fmt"
    "github.com/aliyun/aliyun-oss-go-sdk/oss"
    "os"
)

func HandleError(err error) {
    fmt.Println("Error:", err)
    os.Exit(-1)
}

func main() {
    // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
    provider, err := oss.NewEnvironmentVariableCredentialsProvider()
    if err != nil {
    fmt.Println("Error:", err)
    os.Exit(-1)
    }

    // Create an OSSClient instance. 
    // Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
    client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider))
    if err != nil {
    HandleError(err)
    }

    // Specify the name of the bucket in which the source image is stored. Example: srcbucket. 
    bucketName := "SourceBucketName"
    bucket, err := client.Bucket(bucketName)
    if err != nil {
    HandleError(err)
    }
    // Specify the name of the source image. If the source image is not stored in the root directory of the bucket, you must specify the full path of the image. Example: example/example.jpg. 
    sourceImageName := "yourObjectName"
    // Specify the name of the bucket to which you want to store the processed image. The bucket must be located in the same region as the bucket in which the source image is stored. 
    targetBucketName := "TargetBucketName"
    // Specify the name of the processed image. If the processed image is not stored in the root directory of the bucket, you must specify the full path of the image. Example: exampledir/example.jpg. 
    targetImageName := "TargetObjectName"
    // Resize the image to 100 x 100 pixels and save the image to a specific bucket. 
    style := "image/resize,m_fixed,w_100,h_100"
    process := fmt.Sprintf("%s|sys/saveas,o_%v,b_%v", style, base64.URLEncoding.EncodeToString([]byte(targetImageName)), base64.URLEncoding.EncodeToString([]byte(targetBucketName)))
    result, err := bucket.ProcessObject(sourceImageName, process)
    if err != nil {
    HandleError(err)
    } else {
    fmt.Println(result)
    }
}

Generate a signed object URL that includes IMG parameters

The URL of a private object is signed. IMG parameters cannot be directly added to the end of a signed URL. If you want to process a private object, add IMG parameters to the signature. The following sample code provides an example on how to add IMG parameters to a signature:

package main

import (
    "fmt"
    "os"
    "github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func HandleError(err error) {
    fmt.Println("Error:", err)
    os.Exit(-1)
}

func main() {
    // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
    provider, err := oss.NewEnvironmentVariableCredentialsProvider()
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }

    // Create an OSSClient instance. 
    // Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
    client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider))
    if err != nil {
    HandleError(err)
    }

    // Specify the name of the bucket in which the source image is stored. Example: examplebucket. 
    bucketName := "examplebucket"
    bucket, err := client.Bucket(bucketName)
    if err != nil {
    HandleError(err)
    }
    // Specify the name of the image. If the image is not stored in the root directory of the bucket, you must specify the full path of the image. Example: exampledir/example.jpg. 
    ossImageName := "exampledir/example.jpg"
    // Generate a signed URL that includes IMG parameters. Set the validity period of the signed URL to 600 seconds. 
    signedURL, err := bucket.SignURL(ossImageName, oss.HTTPGet, 600, oss.Process("image/format,png"))
    if err != nil {
    HandleError(err)
    } else {
    fmt.Println(signedURL)
    }
}

References

For more information about the supported IMG parameters, see IMG parameters.