> ## Documentation Index
> Fetch the complete documentation index at: https://www.ayrshare.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# 调整图片尺寸

> 将图片调整为社交媒体尺寸、添加水印或裁剪

export const HeaderAPI = ({noProfileKey, profileKeyRequired}) => <>
    <ParamField header="Authorization" type="string" required>
      <a href="/apis/overview#authorization">API Key</a> of the Primary Profile.
      <br />
      <br />
      Format: <code>Authorization: Bearer API_KEY</code>
    </ParamField>
    {!noProfileKey && (profileKeyRequired ? <ParamField header="Profile-Key" type="string" required>
          <a href="/apis/overview#profile-key-format">Profile Key</a> of a User Profile.
          <br />
          <br />
          Format: <code>Profile-Key: PROFILE_KEY</code>
        </ParamField> : <ParamField header="Profile-Key" type="string">
          <a href="/apis/overview#profile-key-format">Profile Key</a> of a User Profile.
          <br />
          <br />
          Format: <code>Profile-Key: PROFILE_KEY</code>
        </ParamField>)}
  </>;

export const PlansAvailable = ({plans = [], maxPackRequired}) => {
  let displayPlans = plans;
  if (plans && plans.length === 1) {
    const lowerCasePlan = plans[0].toLowerCase();
    if (lowerCasePlan === "business") {
      displayPlans = ["Launch", "Business", "Enterprise"];
    } else if (lowerCasePlan === "premium") {
      displayPlans = ["Premium", "Launch", "Business", "Enterprise"];
    }
  }
  return <Note>
Available on {displayPlans.length === 1 ? "the " : ""}
{displayPlans.join(", ").replace(/\b\w/g, l => l.toUpperCase())}{" "}
{displayPlans.length > 1 ? "plans" : "plan"}.

{maxPackRequired && <span onClick={() => window.open('https://www.ayrshare.com/docs/additional/maxpack', '_self')} className="flex items-center mt-2 cursor-pointer">
 <span className="px-1.5 py-0.5 rounded text-sm" style={{
    backgroundColor: '#C264B6',
    color: 'white',
    fontSize: '12px'
  }}>
   Max Pack required
 </span>
</span>}
</Note>;
};

<PlansAvailable plans={["premium"]} maxPackRequired={true} />

各社交网络对社交媒体图片有[特定要求](/media-guidelines)。resize 端点允许你选择兼容各社交网络的图片尺寸,添加水印、更换背景、添加特效、裁剪等。

默认情况下,调整尺寸会改变图片的尺寸,但不会裁剪图片。你也可以选择裁剪图片。详见下文。

## Header Parameters

<HeaderAPI noProfileKey={true} />

## Body Parameters

<ParamField body="imageUrl" type="string" required>
  待调整尺寸的图片 URL。必须以 `https://` 开头。
</ParamField>

<ParamField body="platform" type="array" required>
  要为哪个社交媒体平台调整 URL。详见[平台选项](/apis/media/resize#platform-options)。
</ParamField>

<ParamField body="file" type="object">
  以 multipart form-data 对象形式发送媒体文件。当未提供 `imageUrl` 时必填。
</ParamField>

<ParamField body="watermark" type="object">
  应用到调整后图片上的水印 URL 及可选位置。默认情况下,水印会出现在图片的右下角。详见[watermark](/apis/media/resize#watermark)。
</ParamField>

<ParamField body="effects" type="string">
  更改不透明度、颜色等。详见[effects options](/apis/media/resize#effects-options)。
</ParamField>

<ParamField body="dimensions" type="object">
  指定调整尺寸的 `width` 和 `height` 的对象。若为裁剪,可选择性地指定中心 `x` 和 `y` 坐标。
  默认为图片中心。

  ```json Dimensions theme={"system"}
  {
    "width": 500,
    "height": 500,
    "xCoordinate": 35, // optional for crop mode
    "yCoordinate": 50 // optional for crop mode
  }
  ```

  <Note>如果未指定 platform,则 width 和 height 必填。</Note>
</ParamField>

<ParamField body="mode" type="string" default="resize">
  取值:`resize`、`blur` 或 `crop`。详见[mode](/apis/media/resize#mode)。
</ParamField>

<ParamField body="convertToJpg" type="boolean">
  自动将文件转换为 JPG,例如将 PNG 转换为 JPG。将使用 75% 的质量。
  详见[转换为 JPG](/apis/media/resize#convert-to-a-jpg-or-webp)。
</ParamField>

<ParamField body="convertToWebP" type="boolean">
  自动将文件转换为 WebP,例如将 PNG 转换为 WebP。将使用 75% 的质量。
  详见[转换为 WebP](/apis/media/resize#convert-to-a-jpg-or-webp)。
</ParamField>

### 平台选项

以字符串形式指定平台,即可使用预定义的图片尺寸,你也可以通过 `dimensions` 字段自定义。

例如,`"platform": "facebook"` 将把图片尺寸设置为宽 1200px、高 630px。

<ul class="custom-bullets">
  <li>`facebook`:宽 1200px,高 630px。</li>
  <li>`instagram`:宽 1080px,高 1080px。</li>
  <li>`instagram_landscape`:宽 1080px,高 680px。</li>
  <li>`instagram_portrait`:宽 1080px,高 1920px。</li>
  <li>`instagram_special`:宽 1080px,高 800px。</li>
  <li>`linkedin`:宽 1200px,高 627px。</li>
  <li>`pinterest`:宽 1080px,高 1920px。</li>
  <li>`tiktok`:宽 1080px,高 1920px。</li>
  <li>`twitter`:宽 1600px,高 900px。</li>
</ul>

请注意,按这些尺寸调整不会裁剪图片。
如果你想裁剪图片,可以将 `mode` 参数设为 `crop`,并配合 `dimensions` 以及 `xCoordinate`、`yCoordinate` 字段。

### Mode

#### Resize

Resize 是默认模式,会在保持宽高比的同时改变图片尺寸。
将图片调整为指定尺寸,而不裁剪任何内容。

示例 JSON:

```json Resize theme={"system"}
{
  "mediaUrl": "https://img.ayrshare.com/012/gb.jpg",
  "platform": "instagram",
  "mode": "resize"
}
```

你也可以使用 `dimensions` 字段指定自定义尺寸:

```json Resize with Dimensions theme={"system"}
{
  "mediaUrl": "https://img.ayrshare.com/012/gb.jpg",
  "mode": "resize",
  "dimensions": {
    "width": 800,
    "height": 600
  }
}
```

必须指定 `platform`,或者 `dimensions` 中的 `width` 和 `height`。

#### Crop

Crop 会将图片"裁切"至指定尺寸。默认中心坐标为图片中心。你也可以指定自己的 x/y 坐标。

示例 JSON:

```json Crop theme={"system"}
{
  "mediaUrl": "https://img.ayrshare.com/012/gb.jpg",
  "platform": "instagram",
  "mode": "crop"
}
```

你也可以使用 `dimensions` 字段指定自定义尺寸和可选的裁剪坐标:

```json Crop with Dimensions theme={"system"}
{
  "mediaUrl": "https://img.ayrshare.com/012/gb.jpg",
  "mode": "crop",
  "dimensions": {
    "width": 1080,
    "height": 1080,
    "xCoordinate": 35,
    "yCoordinate": 50
  }
}
```

必须指定 `platform`,或者 `dimensions` 中的 `width` 和 `height`。

对于方形裁剪,如果 `width` 或 `height` 小于所提供图片的尺寸,则会使用 `width` 或 `height` 中较小的那个值。例如,若图片为 1200x800 而请求的裁剪尺寸为 1080x1080,返回的图片将为 800x800。

#### Blur

Blur 效果会复制一份图片作为背景,并对其进行模糊处理。

示例 blur JSON:

```json Blur theme={"system"}
{
  "mediaUrl": "https://img.ayrshare.com/012/gb.jpg",
  "platform": "instagram",
  "mode": "blur"
}
```

模糊效果示例图:

<img src="https://mintcdn.com/ayrshare-docs/Nmrhj2Gh7WSf62Bh/images/apis/media/blur.webp?fit=max&auto=format&n=Nmrhj2Gh7WSf62Bh&q=85&s=8877f9f348f319fc683bc7928d767dbb" alt="Background with Blur" width="1080" height="1080" data-path="images/apis/media/blur.webp" />

### Watermark

#### 水印概览

你可以通过提供一个必须以 `https://` 开头的 URL(以及可选的位置)为图片添加水印。
默认情况下,水印会出现在图片的右下角 —— `southeast`。

我们建议使用带透明背景的 PNG。

示例 watermark JSON:

```json Watermark theme={"system"}
{
  "mediaUrl": "https://img.ayrshare.com/random/photo-13.jpg",
  "platform": "instagram",
  "watermark": {
    "url": "https://img.ayrshare.com/012/100-percent.png",
    "position": "northeast" // optional
  }
}
```

位于 southeast 位置的水印示例图:

<img src="https://mintcdn.com/ayrshare-docs/Nmrhj2Gh7WSf62Bh/images/apis/media/watermark.webp?fit=max&auto=format&n=Nmrhj2Gh7WSf62Bh&q=85&s=7794b66e76cfa988131ab99232af9081" alt="Add Watermark" width="1080" height="1080" data-path="images/apis/media/watermark.webp" />

#### 水印位置

水印位置可以是以下值之一:

<ul class="custom-bullets">
  <li>`north`</li>
  <li>`northeast`</li>
  <li>`east`</li>
  <li>`southeast`</li>
  <li>`south`</li>
  <li>`southwest`</li>
  <li>`west`</li>
  <li>`northwest`</li>
  <li>`center`</li>
</ul>

### Effects 选项

#### 十六进制颜色

背景模糊颜色的十六进制值。仅当 `"mode": "blur"` 时适用。字符串值,例如 `"#A020F0"`。

示例背景色 JSON:

```json Color Background theme={"system"}
{
  "mediaUrl": "https://img.ayrshare.com/012/gb.jpg",
  "platform": "instagram",
  "mode": "blur",
  "effects": {
    "color": "#A020F0"
  }
}
```

背景色示例图:

<img src="https://mintcdn.com/ayrshare-docs/Nmrhj2Gh7WSf62Bh/images/apis/media/color-background.webp?fit=max&auto=format&n=Nmrhj2Gh7WSf62Bh&q=85&s=07c06abcfac8e792c361cc8eaa9884a1" alt="Add Colored Background" width="1080" height="1080" data-path="images/apis/media/color-background.webp" />

#### 颜色:灰度、复古、反色

你可以通过指定 `grayscale`、`sepia` 或 `invert` 更改图片的主色调。`"blur": true` 字段不是必需的,如果你不想要背景,请勿使用。

示例灰度 JSON:

```json Grayscale theme={"system"}
{
  "mediaUrl": "https://img.ayrshare.com/random/photo-13.jpg",
  "platform": "instagram",
  "effects": {
    "color": "grayscale"
  }
}
```

灰度示例图:

<img src="https://mintcdn.com/ayrshare-docs/Nmrhj2Gh7WSf62Bh/images/apis/media/grayscale.webp?fit=max&auto=format&n=Nmrhj2Gh7WSf62Bh&q=85&s=c654e1485a00be0d421d4ffa19ebfbc7" alt="Add Grayscale" width="1080" height="1080" data-path="images/apis/media/grayscale.webp" />

#### 不透明度

设置图片的不透明度。数值范围:0 - 1。

示例 opacity JSON:

```json Opacity theme={"system"}
{
  "effects": {
    "opacity": 0.2
  }
}
```

#### 质量

对于 JPG 或 JEPG 图片,可指定图片的质量(即压缩程度)。
数值越低压缩越强,但图片质量越低。
数值越高压缩越弱,但图片质量越高。数值范围:0 - 100。

示例 quality JSON:

```json Quality theme={"system"}
{
  "effects": {
    "quality": 20
  }
}
```

### 转换为 JPG 或 WebP

`convertToJpg` 和 `convertToWebP` 选项允许你将图片从其原始格式(例如 PNG)分别转换为 JPG 或 WebP 格式。
默认情况下,转换后的图片使用 75% 的质量设置。

你可以通过 effects 对象中的 [quality](/apis/media/resize#quality) 参数自定义压缩级别。

请注意,如果源图片已经是 JPG 且你使用了 `convertToJpg`,API 只会将图片调整为指定尺寸,而不会改变格式。

示例转换为 JPG:

```json Convert to JPG theme={"system"}
{
  "convertToJpg": true
}
```

示例转换为 WebP:

```json Convert to WebP theme={"system"}
{
  "convertToWebP": true
}
```

<RequestExample>
  ```bash cURL theme={"system"}
    curl \
    -H "Authorization: Bearer API_KEY" \
    -H 'Content-Type: application/json' \
    -d '{"mediaUrl": "https://img.ayrshare.com/012/gb.jpg", "platform": "instagram"' \
    -X POST https://api.ayrshare.com/api/media/resize
  ```

  ```javascript JavaScript theme={"system"}
  const API_KEY = "API_KEY";

  fetch("https://api.ayrshare.com/api/media/resize", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${API_KEY}`
    },
    body: JSON.stringify({
      mediaUrl: "https://img.ayrshare.com/012/gb.jpg", // required
      platform: "instagram"
    })
  })
    .then((res) => res.json())
    .then((json) => console.log(json))
    .catch(console.error);
  ```

  ```python Python theme={"system"}
  import requests

  payload = {'mediaUrl': 'https://img.ayrshare.com/012/gb.jpg',
          'platforms': 'instagram'}
  headers = {'Content-Type': 'application/json',
          'Authorization': 'Bearer API_KEY'}

  r = requests.post('https://api.ayrshare.com/api/media/resize',
      json=payload,
      headers=headers)

  print(r.json())
  ```

  ```php PHP theme={"system"}
  <?php

  $curl = curl_init();
  $data = array (
    "mediaUrl" => "https://img.ayrshare.com/012/gb.jpg",
    "platforms" => "instagram"
  );

  curl_setopt_array($curl, array(
    CURLOPT_URL => 'https://api.ayrshare.com/api/media/resize',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => '',
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_POSTFIELDS => http_build_query($data),
    CURLOPT_HTTPHEADER => array(
      'Authorization: Bearer API_KEY',
      'Accept-Encoding: gzip'
    ),
  ));

  $response = curl_exec($curl);
  curl_close($curl);
  echo $response;
  ```

  ```csharp C# theme={"system"}
  using System;
  using System.Net.Http;
  using System.Text;
  using System.Text.Json;
  using System.Threading.Tasks;

  public class AyrshareApiClient
  {
      private readonly HttpClient _httpClient;
      private readonly string _apiKey;
      private const string BaseUrl = "https://api.ayrshare.com/api";

      public AyrshareApiClient(string apiKey)
      {
          _apiKey = apiKey ?? throw new ArgumentNullException(nameof(apiKey));
          _httpClient = new HttpClient();
          _httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {_apiKey}");
      }

      public async Task<string> ResizeMediaAsync(string mediaUrl, string platform)
      {
          try
          {
              var requestData = new
              {
                  mediaUrl = mediaUrl,
                  platform = platform
              };

              var content = new StringContent(
                  JsonSerializer.Serialize(requestData),
                  Encoding.UTF8,
                  "application/json"
              );

              var response = await _httpClient.PostAsync($"{BaseUrl}/media/resize", content);
              response.EnsureSuccessStatusCode();

              var jsonResponse = await response.Content.ReadAsStringAsync();
              return jsonResponse;
          }
          catch (HttpRequestException ex)
          {
              throw new Exception($"Failed to resize media: {ex.Message}", ex);
          }
      }

      public void Dispose()
      {
          _httpClient.Dispose();
      }
  }
  ```
</RequestExample>

<ResponseExample>
  ```json 200: Success theme={"system"}
  {
    "status": "success",
    "url": "https://media.ayrshare.com/9abf1426d6ce9122ef11c72bd62e59807c5cc083/8UbyBjHTxgHkAC1I37e6O.jpg",
    "platform": "instagram",
    "mode": "blur",
    "effects": {
      "color": "#A020F0"
    }
  }
  ```

  ```json 400: Failed Resize theme={"system"}
  {
    "action": "resize",
    "status": "error",
    "code": 312,
    "message": "Invalid extension type. Extension: null. Please verify the extension is one of the following: png, jpg, jpeg and the file is accessible."
  }
  ```
</ResponseExample>
