Tous les produits
Search
Centre de documentation

Object Storage Service:Traitement d'images (SDK C# v1)

Dernière mise à jour :Aug 27, 2026

Le service de traitement d'images (IMG) est un service sécurisé, économique et hautement fiable fourni par Object Storage Service (OSS) pour vous aider à traiter de grands volumes de données. Après avoir téléchargé vos images sources vers OSS, vous pouvez appeler des opérations d'API REST pour les traiter depuis n'importe quel appareil connecté à Internet, à tout moment et en tout lieu.

Notes

  • Cette rubrique utilise le point de terminaison public de la région Chine (Hangzhou). Si vous souhaitez accéder à OSS depuis d'autres services Alibaba Cloud situés dans la même région, utilisez un point de terminaison interne. Pour plus d'informations sur les régions et les points de terminaison OSS, consultez Régions et points de terminaison.

  • Cette rubrique illustre la création d'une instance OSSClient avec un point de terminaison OSS. Pour d'autres configurations, telles que l'utilisation d'un domaine personnalisé ou l'authentification via des identifiants du Security Token Service (STS), consultez Initialisation (SDK C# V1).

Utiliser des paramètres IMG pour traiter une image

  • Utilisez un seul paramètre IMG pour traiter une image et enregistrez-la sur votre ordinateur local.

    using System;
    using System.IO;
    using Aliyun.OSS;
    using Aliyun.OSS.Common;
    using Aliyun.OSS.Util;
    
    namespace Samples
    {
        public class Program
        {
            public static void Main(string[] args)
            {
                // 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. 
                var endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
                // 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.  
                var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
                var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
                // Specify the name of the bucket in which the source image is stored. Example: examplebucket. 
                var bucketName = "examplebucket";
                // 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 object. Example: exampledir/example.jpg. 
                var objectName = "exampledir/example.jpg";
                // Specify the local path of the source image. 
                var localImageFilename = "D:\\localpath\\example.jpg";
                // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
                const string region = "cn-hangzhou";
                
                // Create a ClientConfiguration instance and modify the default parameters based on your requirements.
                var conf = new ClientConfiguration();
                
                // Use the signature algorithm V4.
                conf.SignatureVersion = SignatureVersion.V4;
                
                // Create an OSSClient instance.
                var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
                client.SetRegion(region);
                try
                {
                    // Resize the image to 100 × 100 pixels. 
                    var process = "image/resize,m_fixed,w_100,h_100";
                    var ossObject = client.GetObject(new GetObjectRequest(bucketName, objectName, process));
                    // Specify the name of the processed image. 
                    WriteToFile(localImageFilename, ossObject.Content);
                }
                catch (OssException ex)
                {
                    Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                        ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Failed with error info: {0}", ex.Message);
                }
            }
            private static void WriteToFile(string filePath, Stream stream)
            {
                using (var requestStream = stream)
                {
                    using (var fs = File.Open(filePath, FileMode.OpenOrCreate))
                    {
                        IoUtils.WriteTo(stream, fs);
                    }
                }
            }
        }
    }
  • Utilisez différents paramètres IMG pour traiter une image et enregistrez séparément les résultats sur votre ordinateur local.

    using System;
    using System.IO;
    using Aliyun.OSS;
    using Aliyun.OSS.Common;
    using Aliyun.OSS.Util;
    namespace Samples
    {
        public class Program
        {
            public static void Main(string[] args)
            {
                // 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. 
                var endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
                // 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.  
                var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
                var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
                // Specify the name of the bucket in which the source image is stored. Example: examplebucket. 
                var bucketName = "examplebucket";
                // 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 object. Example: exampledir/example.jpg. 
                var objectName = "exampledir/example.jpg";
                // Specify the local path of the source image. 
                var localImageFilename = "D:\\localpath\\example.jpg";
                // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
                const string region = "cn-hangzhou";
                
                // Create a ClientConfiguration instance and modify the default parameters based on your requirements.
                var conf = new ClientConfiguration();
                
                // Use the signature algorithm V4.
                conf.SignatureVersion = SignatureVersion.V4;
                
                // Create an OSSClient instance.
                var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
                client.SetRegion(region);
                try
                {
                    // If the image does not exist in the specified bucket, upload the image to the bucket.    
                    // client.PutObject(bucketName, objectName, localImageFilename);
                    // Resize the image to 100 × 100 pixels. 
                    var process = "image/resize,m_fixed,w_100,h_100";
                    var ossObject = client.GetObject(new GetObjectRequest(bucketName, objectName, process));
                    // Specify the name of the processed image. 
                    WriteToFile(localImageFilename, ossObject.Content);
                    // Crop the image to 100 × 100 pixels starting from the position specified by coordinate pair (100, 100). 
                    process = "image/crop,w_100,h_100,x_100,y_100";
                    ossObject = client.GetObject(new GetObjectRequest(bucketName, objectName, process));
                    WriteToFile(localImageFilename , ossObject.Content);
                    // Rotate the image 90 degrees. 
                    process = "image/rotate,90";
                    ossObject = client.GetObject(new GetObjectRequest(bucketName, objectName, process));
                    WriteToFile(localImageFilename , ossObject.Content);
                }
                catch (OssException ex)
                {
                    Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                        ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Failed with error info: {0}", ex.Message);
                }
            }
            private static void WriteToFile(string filePath, Stream stream)
            {
                using (var requestStream = stream)
                {
                    using (var fs = File.Open(filePath, FileMode.OpenOrCreate))
                    {
                        IoUtils.WriteTo(stream, fs);
                    }
                }
            }
        }
    }
  • Combinez plusieurs paramètres IMG pour traiter une image et enregistrez le résultat sur votre ordinateur local.

    L'exemple de code suivant montre comment utiliser plusieurs paramètres IMG pour traiter une image. Les paramètres IMG sont séparés par des barres obliques (/).

    using System;
    using System.IO;
    using Aliyun.OSS;
    using Aliyun.OSS.Common;
    using Aliyun.OSS.Util;
    namespace ImageProcessCascade
    {
        class Program
        {
            static void Main(string[] args)
            {
                Program.ImageProcessCascade();
                Console.ReadKey();
            }
            public static void ImageProcessCascade()
            {
                // 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. 
                var endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
                // 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.  
                var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
                var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
                // Specify the name of the bucket in which the source image is stored. Example: examplebucket. 
                var bucketName = "examplebucket";
                // 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 object. Example: exampledir/example.jpg. 
                var objectName = "exampledir/example.jpg";
                // Specify the local path of the source image. 
                var localImageFilename = "D:\\localpath\\example.jpg";
                // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
                const string region = "cn-hangzhou";
                
                // Create a ClientConfiguration instance and modify the default parameters based on your requirements.
                var conf = new ClientConfiguration();
                
                // Use the signature algorithm V4.
                conf.SignatureVersion = SignatureVersion.V4;
                
                // Create an OSSClient instance.
                var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
                client.SetRegion(region);
                try
                {
                    // If the source image does not exist in the specified bucket, upload the image to the bucket.    
                    // client.PutObject(bucketName, objectName, localImageFilename);
                    // After you resize the image to 100 × 100 pixels, rotate the image 90 degrees. 
                    var process = "image/resize,m_fixed,w_100,h_100/rotate,90";
                    var ossObject = client.GetObject(new GetObjectRequest(bucketName, objectName, process));
                    // Specify the name of the processed image. 
                    WriteToFile(localImageFilename, ossObject.Content);
                    Console.WriteLine("Get Object:{0} with process:{1} succeeded ", objectName, process);
                }
                catch (OssException ex)
                {
                    Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                        ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Failed with error info: {0}", ex.Message);
                }
            }
            private static void WriteToFile(string filePath, Stream stream)
            {
                using (var requestStream = stream)
                {
                    using (var fs = File.Open(filePath, FileMode.OpenOrCreate))
                    {
                        IoUtils.WriteTo(stream, fs);
                    }
                }
            }
        }
    }

Utiliser un style d'image pour traiter une image

Vous pouvez regrouper plusieurs paramètres IMG dans un style, puis utiliser ce style pour traiter une image. Pour plus d'informations, consultez Styles d'image. L'exemple de code suivant montre comment utiliser un style d'image pour traiter une image :

using System;
using System.IO;
using Aliyun.OSS;
using Aliyun.OSS.Common;
using Aliyun.OSS.Util;
namespace ImageProcessCustom
{
    class Program
    {
        static void Main(string[] args)
        {
            Program.ImageProcessCustomStyle();
            Console.ReadKey();
        }
        public static void ImageProcessCustomStyle()
        {
            // 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. 
            var endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // 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.  
            var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
            var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
            // Specify the name of the bucket in which the source image is stored. Example: examplebucket. 
            var bucketName = "examplebucket";
            // 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 object. Example: exampledir/example.jpg. 
            var objectName = "exampledir/example.jpg";
            // Specify the local path of the source image. 
            var localImageFilename = "D:\\localpath\\example.jpg";
            // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
            const string region = "cn-hangzhou";
            
            // Create a ClientConfiguration instance and modify the default parameters based on your requirements.
            var conf = new ClientConfiguration();
            
            // Use the signature algorithm V4.
            conf.SignatureVersion = SignatureVersion.V4;
            
            // Create an OSSClient instance.
            var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
            client.SetRegion(region);
            try
            {
                // If the source image does not exist in the specified bucket, upload the image to the bucket.    
                // client.PutObject(bucketName, objectName, localImageFilename);
                // Use the image style to process the image. In this example, replace yourCustomStyleName with the name of the image style that you created in the OSS console. 
                var process = "style/yourCustomStyleName";
                var ossObject = client.GetObject(new GetObjectRequest(bucketName, objectName, process));
                // Specify the name of the processed image.             
                WriteToFile(localImageFilename, ossObject.Content);
                Console.WriteLine("Get Object:{0} with process:{1} succeeded ", objectName, process);
            }
            catch (OssException ex)
            {
                Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                    ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed with error info: {0}", ex.Message);
            }
        }
        private static void WriteToFile(string filePath, Stream stream)
        {
            using (var requestStream = stream)
            {
                using (var fs = File.Open(filePath, FileMode.OpenOrCreate))
                {
                    IoUtils.WriteTo(stream, fs);
                }
            }
        }
    }
}

Générer une URL d'objet signée incluant des paramètres IMG

Les URL des objets privés doivent être signées. Il n'est pas possible d'ajouter directement des paramètres IMG à la fin d'une URL signée. Pour traiter un objet image privé, vous devez intégrer les paramètres IMG dans la signature. L'exemple de code suivant montre comment ajouter des paramètres IMG à une signature :

using Aliyun.OSS;
using Aliyun.OSS.Common;

// 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. 
var endpoint = "yourEndpoint";
// 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.  
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID"); 
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the name of the bucket in which the source image is stored. Example: examplebucket. 
var bucketName = "examplebucket";
// 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: exampledir/example.jpg. 
var objectName = "exampledir/exampledir.jpg";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
const string region = "cn-hangzhou";

// Create a ClientConfiguration instance and modify the default parameters based on your requirements.
var conf = new ClientConfiguration();

// Use the signature algorithm V4.
conf.SignatureVersion = SignatureVersion.V4;

// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
    // Resize the image to 100 × 100 pixels. 
    var process = "image/resize,m_fixed,w_100,h_100";
    var req = new GeneratePresignedUriRequest(bucketName, objectName, SignHttpMethod.Get)
    {
        Expiration = DateTime.Now.AddHours(1),
        Process = process
    };
    // Generate a signed URL. 
    var uri = client.GeneratePresignedUri(req);
    Console.WriteLine("Generate Presigned Uri:{0} with process:{1} succeeded ", uri, process);
}
catch (OssException ex)
{
    Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
        ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
catch (Exception ex)
{
    Console.WriteLine("Failed with error info: {0}", ex.Message);
}

Références

  • Pour consulter l'exemple de code complet relatif au service IMG, rendez-vous sur GitHub.

  • Pour plus d'informations sur les paramètres IMG pris en charge, consultez Paramètres IMG.