# oss-image-processing

Part of **OSS**

# Object Storage Service Image Processing

## Capabilities Overview

| Sub-capability | Calling Mode | Description |
|----------------|--------------|-------------|
| Create Image Style | Synchronous | Creates a named image style with one or more IMG processing parameters (e.g., resize, quality). |
| Get Image Style Info | Synchronous | Retrieves details of a specific image style by name, including its transformation rules and metadata. |
| List Image Styles | Synchronous | Returns all image styles configured for a given OSS bucket. |
| Delete Image Style | Synchronous | Removes a specified image style from the bucket if it exists and is not in active use. |

## API Calling Patterns

### Authentication
Use **OSS Signature Version 4** (HMAC-SHA256) as the primary authentication method.

- Include the `Authorization` header in every request:
```text
  Authorization: OSS4-HMAC-SHA256 Credential=<AccessKeyID>/<YYYYMMDD>/<region>/oss/aliyun_v4_request,Signature=<SignatureValue>
  ```
- Store credentials securely using environment variables:
  - `ALIBABA_CLOUD_ACCESS_KEY_ID`
  - `ALIBABA_CLOUD_ACCESS_KEY_SECRET`

While presigned URLs and STS tokens are supported for temporary access, direct signature-based auth is recommended for server-side integrations.

### Service Endpoint
APIs use region-specific endpoints following this pattern:

```text
https://{bucket-name}.{region}.aliyuncs.com
```

Common regions include:
- `cn-hangzhou`
- `cn-shanghai`
- `oss-cn-shanghai`

All image style operations are bucket-level and appended as query parameters (e.g., `?style&styleName=my-style`).

### Synchronous Request Flow
All image style management APIs (`PutStyle`, `GetStyle`, `ListStyle`, `DeleteStyle`) are 
1. Construct the full URL with required query parameters.
2. Sign the request using your AccessKey pair and the current date/region.
3. Send the HTTP request (PUT, GET, or DELETE) with proper headers.
4. Parse the immediate response:
   - Success: HTTP 200 (for PUT/GET/LIST) or 204 (for DELETE)
   - Error: HTTP 4xx/5xx with error code and message

No polling or async result fetching is needed.

## Parameter Reference

### Create Image Style (PutStyle)

| Parameter | Type | Required | Default | Constraints | Description |
|----------|------|--------|--------|------------|------------|
| styleName | string | Yes | — | Must be unique within the bucket | The name of the image style to create. |
| Content | string | Yes | — | Valid IMG parameter string (e.g., `image/resize,p_50`) | One or more chained image processing commands using OSS IMG syntax. |

### Get Image Style Info (GetStyle)

| Parameter | Type | Required | Default | Constraints | Description |
|----------|------|--------|--------|------------|------------|
| styleName | string | Yes | — | Must match an existing style | The name of the image style to retrieve. |

### Delete Image Style (DeleteStyle)

| Parameter | Type | Required | Default | Constraints | Description |
|----------|------|--------|--------|------------|------------|
| style | string | Yes | — | Must be the target bucket name | The name of the bucket containing the style. |
| styleName | string | Yes | — | Must exist and not be in active use | The name of the image style to delete. |

> **Note**: The `style` parameter in `DeleteStyle` appears to be redundant in practice (the bucket is already in the hostname), but is required per API specification.

## Code Examples

### Create Image Style - Python - cn-hangzhou

```python
import oss2

auth = oss2.Auth('your-access-key-id', 'your-access-key-secret')
bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'oss-example')

# Create a style that resizes to 50% and sets quality to 90
style_name = 'thumbnail_style'
style_content = 'image/resize,p_50/quality,q_90'

bucket.put_style(style_name, style_content)
print(f"Style '{style_name}' created.")
```

### Get Image Style Info - Python - all regions

```python
import oss2

auth = oss2.Auth('your-access-key-id', 'your-access-key-secret')
bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'oss-example')

style_name = 'imagestyle'
result = bucket.get_style(style_name)
print("Name:", result.name)
print("Content:", result.content)
print("Category:", result.category)
print("Created:", result.create_time)
print("Modified:", result.last_modify_time)
```

### List All Image Styles - Bash - cn-hangzhou

```bash
ossutil liststyle oss://oss-example --endpoint=oss-cn-hangzhou.aliyuncs.com
```

### Delete Image Style - HTTP Request - all regions

```http
DELETE /?style=oss-example&styleName=imagestyle HTTP/1.1
Date: Thu, 17 Apr 2025 05:38:38 GMT
Host: oss-example.oss-cn-hangzhou.aliyuncs.com
Authorization: OSS4-HMAC-SHA256 Credential=LTAI********************/20250417/cn-hangzhou/oss/aliyun_v4_request,Signature=a7c3554c729d71929e0b84489addee6b2e8d5cb48595adfc51868c299c0c218e
```

### Create Image Style via Raw HTTP - plaintext - all regions

```http
PUT /?style&styleName=imagestyle HTTP/1.1
Date: Thu, 17 Apr 2025 05:34:24 GMT
Content-Length: 63
Host: oss-example.oss-cn-hangzhou.aliyuncs.com
Authorization: OSS4-HMAC-SHA256 Credential=LTAI********************/20250417/cn-hangzhou/oss/aliyun_v4_request,AdditionalHeaders=content-length,Signature=a7c3554c729d71929e0b84489addee6b2e8d5cb48595adfc51868c299c0c218e
<Style>
 <Content>image/resize,p_50</Content>
</Style>
```

## Response Format

### GetStyle / ListStyle Success Response (XML)

```xml
<?xml version="1.0" encoding="UTF-8"?>
<Style>
 <Name>imagestyle</Name>
 <Content>image/resize,p_50</Content>
 <Category>image</Category>
 <CreateTime>Wed, 20 May 2020 12:07:15 GMT</CreateTime>
 <LastModifyTime>Wed, 21 May 2020 12:07:15 GMT</LastModifyTime>
</Style>
```

**Key Fields**:
- `Style.Name` — Name of the image style
- `Style.Content` — IMG transformation rule string
- `Style.Category` — Always "image" for image styles
- `Style.CreateTime` — ISO 8601 timestamp when the style was created
- `Style.LastModifyTime` — ISO 8601 timestamp of last modification

For `ListStyle`, the root element is `<StyleList>` containing multiple `<Style>` blocks.

### DeleteStyle / PutStyle Success Response (HTTP Headers)

```text
HTTP/1.1 204
Server: AliyunOSS
Date: Fri, 04 Mar 2022 05:38:38 GMT
Content-Length: 0
Connection: keep-alive
x-oss-request-id: 6221A5DE5BEABE363779****
```

**Key Fields**:
- `x-oss-request-id` — Unique ID for troubleshooting
- `Content-Length` — Always 0 for non-XML responses
- `Status` — 200 (PutStyle) or 204 (DeleteStyle) indicates success

## Error Handling

| Error Code | Description | Recommended Action |
|-----------|-------------|-------------------|
| 403 | Access denied. The user does not have the required permission (e.g., oss:PutStyle, oss:GetStyle, oss:ListStyle, oss:DeleteStyle). | Attach a RAM policy granting the missing permission to your user/role. |
| 404 | The specified bucket or image style does not exist. | Verify the bucket name, region, and style name. Ensure the bucket exists in the target region. |
| 400 | Bad request. The request body is malformed or contains invalid IMG parameters. | Validate the XML payload and ensure IMG syntax is correct (e.g., `image/resize,w_200`). |

### Rate Limits & Retry
- **QPS Limit**: 100 requests per second per account
- **Style Limit**: Up to 100 image styles per bucket
- **Retry Guidance**: For 429 (Too Many Requests), implement exponential backoff with jitter. Most errors (403, 404, 400) are client-side and should not be retried without correction.

## Environment Requirements

- **Python SDK**: `pip install oss2>=2.0.0`
- **Credentials**: Set environment variables:
  ```bash
  export ALIBABA_CLOUD_ACCESS_KEY_ID=your_key_id
  export ALIBABA_CLOUD_ACCESS_KEY_SECRET=your_key_secret
  ```
- **ossutil**: Download from [Alibaba Cloud OSS Tools](https://help.aliyun.com/zh/oss/developer-reference/ossutil) for CLI operations.

## FAQ

Q: What is an image style in OSS?
A: An image style is a named template of one or more IMG processing parameters (e.g., `image/resize,w_200/quality,q_80`) that can be applied to images on-the-fly via URL. Styles are managed at the bucket level.

Q: Can I apply image styles without creating them first?
A: Yes. You can use raw IMG parameters directly in object URLs (e.g., `example.jpg?x-oss-process=image/resize,w_200`). However, named styles simplify reuse and governance.

Q: Why do I get a 403 error when calling PutStyle?
A: Your RAM user or role lacks the `oss:PutStyle` permission. Attach a policy that includes this action for your bucket.

Q: Are image styles region-specific?
A: Yes. Styles are bound to a bucket, which resides in a specific region. You must use the correct regional endpoint.

Q: How many image styles can I create per bucket?
A: A maximum of 100 image styles per bucket is allowed.

## Pricing & Billing

### Billing Model
Billed **per request** for each API call (PutStyle, GetStyle, ListStyle, DeleteStyle).

### Price Reference

| Operation | Price per Request |
|----------|------------------|
| Any image style management API | ¥0.0001 |

### Free Tier
- First **1,000 requests per month** are free across all image style operations.
- Free tier resets monthly.

### Usage Limits
- **QPS**: 100 requests per second per Alibaba Cloud account
- **Styles per bucket**: Maximum 100

### Billing Notes
- Each API call counts as **one billable operation**, regardless of payload size.
- Deleting unused styles incurs no additional cost beyond the single DeleteStyle request fee.
- Image processing itself (when applied to objects) is billed separately under OSS data processing fees—not covered by this API’s pricing.