Google 幻灯片 API,图像在幻灯片上的定位

Google Slides API, positioning of image on the slide

我正在使用 Google 幻灯片 API 将图像插入 Google 幻灯片,我的代码是

    $emu4M = array('magnitude' => 5500000, 'unit' => 'EMU');
    $requests = array();
    $requests[] = new Google_Service_Slides_Request(array(
      'createImage' => array (
        'objectId' => '303030',
        'url' => $imageUrl,
        'elementProperties' => array(
          'pageObjectId' => $pageId,
          'size' => array(
            'height' => $emu4M,
            'width' => $emu4M
          ),
          'transform' => array(
            'scaleX' => 1,
            'scaleY' => 1,
            'translateX' => 5000,
            'translateY' => 5000,
            'unit' => 'EMU'
          )
        )
      )
    ));

没问题,但是插入的图片是这样的

我希望图像显示在中间并减少顶部的填充。有帮助吗?

幻灯片图像定位的工作原理是根据您给定的大小创建一个矩形,在该矩形中适应实际图像的纵横比,然后应用您的变​​换。因此,如果您提供的尺寸与图片的纵横比不匹配,您通常会得到额外的填充。

确保您提供的尺寸与图像尺寸相匹配,然后对 pageSize 和图像尺寸进行一些计算,找出要使用的 translateX/translateY 的正确值。

Google 幻灯片 API 可能会将您的转换请求结果更改为您未曾询问的内容:

When you create a page element, you can specify a size and transform that provide a certain visual result. However, the API may replace your provided values with other ones that yield the same visual appearance. In general, if you write a size using the API, you are not guaranteed to be returned the same size.

来源:https://developers.google.com/slides/how-tos/transform#the_slides_api_might_refactor_your_values


将图像插入到 Google 幻灯片中心的相对安全的方法是通过 ReplaceAllShapesWithImageRequest 插入。

首先您需要创建占位符形状并将其放置在幻灯片的中央:

然后用您的图像替换形状(Google Apps 脚本语言中的示例):

function insertImageCentered()
{
  var presentation = SlidesApp.getActivePresentation();
  
  var requests = [{
    "replaceAllShapesWithImage": {
      "imageUrl": "https://docs.google.com/drawings/d/e/2PACX-1vR5mi6ujksb_2WtTFmk39IPYBIBlJ6WkzM1nsys9cT4Wquik627DDIRXzoYTgHPKX3fcvJzG9inDmJt/pub?w=960&h=720",
        "imageReplaceMethod": "CENTER_INSIDE",
        "pageObjectIds": [presentation.getSlides()[0].getObjectId()],
        "containsText": {
          "text": "{{CENTERED_SHAPE}}",
          "matchCase": false
        }
     }
   }];
  
   Slides.Presentations.batchUpdate({'requests': requests}, presentation.getId());
}

幻灯片中间的结果图像: