影像媒體程式碼範例
此範例示範如何為回應式廣告和影像廣告延伸模組新增媒體。
提示
使用檔標頭中的語言選取器來選擇 C#、JAVA、Php 或 Python。
若要取得 Microsoft Advertising 使用者的存取和重新整理權杖,並使用 Bing 廣告 API 進行您的第一個服務呼叫,請參閱 快速入門 指南。 您會想要檢閱入門指南和慣用語言的逐步解說,例如 C#、 JAVA、 Php和 Python。
GitHub 提供 C#、 JAVA、 Php和 Python 範例的支援檔案。 您可以視需要複製每個存放庫或重新規劃程式碼片段。
using System;
using System.IO;
using System.Linq;
using System.ServiceModel;
using System.Drawing;
using System.Threading.Tasks;
using Microsoft.BingAds.V13.CampaignManagement;
using Microsoft.BingAds;
namespace BingAdsExamplesLibrary.V13
{
/// <summary>
/// How to manage images in an account's media library.
/// </summary>
public class ImageMedia : ExampleBase
{
// To run this example you'll need to provide your own images.
// For required aspect ratios and recommended dimensions please see
// Image remarks at https://go.microsoft.com/fwlink/?linkid=872754.
private const string MediaFilePath = "c:\\dev\\media\\";
private const string ResponsiveAdMediaFileName = "imageresponsivead1200x628.png";
private const string ImageAdExtensionMediaFileName = "imageadextension300x200.png";
public override string Description
{
get { return "Image Media | Campaign Management V13"; }
}
public async override Task RunAsync(AuthorizationData authorizationData)
{
try
{
ApiEnvironment environment = ((OAuthDesktopMobileAuthCodeGrant)authorizationData.Authentication).Environment;
CampaignManagementExampleHelper CampaignManagementExampleHelper = new CampaignManagementExampleHelper(
OutputStatusMessageDefault: this.OutputStatusMessage);
CampaignManagementExampleHelper.CampaignManagementService = new ServiceClient<ICampaignManagementService>(
authorizationData: authorizationData,
environment: environment);
var responsiveAdImageMedia = GetImageMedia(
"Image191x100",
MediaFilePath + ResponsiveAdMediaFileName,
System.Drawing.Imaging.ImageFormat.Png);
var imageAdExtensionMedia = GetImageMedia(
"Image15x10",
MediaFilePath + ImageAdExtensionMediaFileName,
System.Drawing.Imaging.ImageFormat.Png);
var addMedia = new Media[]
{
responsiveAdImageMedia,
imageAdExtensionMedia
};
OutputStatusMessage("Ready to upload image media:");
CampaignManagementExampleHelper.OutputArrayOfMedia(addMedia);
OutputStatusMessage("-----\nAddMedia:");
AddMediaResponse addMediaResponse = await CampaignManagementExampleHelper.AddMediaAsync(
accountId: authorizationData.AccountId,
media: addMedia);
long[] mediaIds = addMediaResponse.MediaIds.ToArray();
OutputStatusMessage("MediaIds:");
CampaignManagementExampleHelper.OutputArrayOfLong(mediaIds);
// Get the media representations to confirm the stored dimensions
// and get the Url where you can later view or download the media.
OutputStatusMessage("-----\nGetMediaMetaDataByAccountId:");
var getResponsiveAdMediaMetaData = (await CampaignManagementExampleHelper.GetMediaMetaDataByAccountIdAsync(
mediaEnabledEntities: MediaEnabledEntityFilter.ResponsiveAd,
pageInfo: null)).MediaMetaData;
OutputStatusMessage("MediaMetaData:");
CampaignManagementExampleHelper.OutputArrayOfMediaMetaData(getResponsiveAdMediaMetaData);
OutputStatusMessage("-----\nGetMediaMetaDataByAccountId:");
var getImageAdExtensionMediaMetaData = (await CampaignManagementExampleHelper.GetMediaMetaDataByAccountIdAsync(
mediaEnabledEntities: MediaEnabledEntityFilter.ImageAdExtension,
pageInfo: null)).MediaMetaData;
OutputStatusMessage("MediaMetaData:");
CampaignManagementExampleHelper.OutputArrayOfMediaMetaData(getImageAdExtensionMediaMetaData);
OutputStatusMessage("-----\nGetMediaMetaDataByIds:");
var getMediaMetaData = (await CampaignManagementExampleHelper.GetMediaMetaDataByIdsAsync(
mediaIds: mediaIds)).MediaMetaData;
OutputStatusMessage("MediaMetaData:");
CampaignManagementExampleHelper.OutputArrayOfMediaMetaData(getMediaMetaData);
// Delete the account's media.
OutputStatusMessage("-----\nDeleteMedia:");
await CampaignManagementExampleHelper.DeleteMediaAsync(
accountId: authorizationData.AccountId,
mediaIds: mediaIds);
foreach (var id in mediaIds)
{
OutputStatusMessage(string.Format("Deleted Media Id {0}", id));
}
}
// Catch authentication exceptions
catch (OAuthTokenRequestException ex)
{
OutputStatusMessage(string.Format("Couldn't get OAuth tokens. Error: {0}. Description: {1}", ex.Details.Error, ex.Details.Description));
}
// Catch Campaign Management service exceptions
catch (FaultException<AdApiFaultDetail> ex)
{
OutputStatusMessage(string.Join("; ", ex.Detail.Errors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
}
catch (FaultException<ApiFaultDetail> ex)
{
OutputStatusMessage(string.Join("; ", ex.Detail.OperationErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
OutputStatusMessage(string.Join("; ", ex.Detail.BatchErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
}
catch (FaultException<EditorialApiFaultDetail> ex)
{
OutputStatusMessage(string.Join("; ", ex.Detail.OperationErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
OutputStatusMessage(string.Join("; ", ex.Detail.BatchErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
}
catch (Exception ex)
{
OutputStatusMessage(ex.Message);
}
}
/// <summary>
/// Get image media that can be managed with the Campaign Management API.
/// </summary>
/// <param name="mediaType">The media type reflects the aspect ratio.</param>
/// <param name="imageFileName">The file name and path.</param>
/// <param name="imageFormat">For supported image formats see <see href="https://go.microsoft.com/fwlink/?linkid=872754">Image remarks</see>.</param>
/// <returns>A Campaign Management Image object.</returns>
private Microsoft.BingAds.V13.CampaignManagement.Image GetImageMedia(
string mediaType,
string imageFileName,
System.Drawing.Imaging.ImageFormat imageFormat)
{
var image = new Microsoft.BingAds.V13.CampaignManagement.Image();
image.Data = GetBmpBase64String(imageFileName, imageFormat);
image.MediaType = mediaType;
image.Type = "Image";
return image;
}
/// <summary>
/// Get the image media as base64 string.
/// </summary>
/// <param name="imageFileName">The file name and path.</param>
/// <param name="imageFormat">For supported image formats see <see href="https://go.microsoft.com/fwlink/?linkid=872754">Image remarks</see>.</param>
/// <returns></returns>
private string GetBmpBase64String(
string imageFileName,
System.Drawing.Imaging.ImageFormat imageFormat)
{
var bmp = new Bitmap(imageFileName);
using (MemoryStream ms = new MemoryStream())
{
bmp.Save(ms, imageFormat);
byte[] imageBytes = ms.ToArray();
string base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
}
}
}
package com.microsoft.bingads.examples.v13;
import java.util.ArrayList;
import java.util.Base64;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.io.File;
import java.nio.file.Files;
import com.microsoft.bingads.*;
import com.microsoft.bingads.v13.campaignmanagement.*;
public class ImageMedia extends ExampleBase {
public static void main(java.lang.String[] args) {
// To run this example you'll need to provide your own images.
// For required aspect ratios and recommended dimensions please see
// Image remarks at https://go.microsoft.com/fwlink/?linkid=872754.
java.lang.String MEDIA_FILE_PATH = "c:\\dev\\media\\";
java.lang.String RESPONSIVE_AD_MEDIA_FILE_NAME = "imageresponsivead1200x628.png";
java.lang.String IMAGE_AD_EXTENSION_MEDIA_FILE_NAME = "imageadextension300x200.png";
try
{
authorizationData = getAuthorizationData();
CampaignManagementExampleHelper.CampaignManagementService = new ServiceClient<ICampaignManagementService>(
authorizationData,
API_ENVIRONMENT,
ICampaignManagementService.class);
Image responsiveAdImageMedia = getImageMedia(
"Image191x100",
MEDIA_FILE_PATH + RESPONSIVE_AD_MEDIA_FILE_NAME);
Image imageAdExtensionMedia = getImageMedia(
"Image15x10",
MEDIA_FILE_PATH + IMAGE_AD_EXTENSION_MEDIA_FILE_NAME);
ArrayOfMedia addMedia = new ArrayOfMedia();
addMedia.getMedias().add(responsiveAdImageMedia);
addMedia.getMedias().add(imageAdExtensionMedia);
outputStatusMessage("Ready to upload image media:");
CampaignManagementExampleHelper.outputArrayOfMedia(addMedia);
outputStatusMessage("-----\nAddMedia:");
ArrayOflong mediaIds = CampaignManagementExampleHelper.addMedia(
authorizationData.getAccountId(),
addMedia).getMediaIds();
outputStatusMessage("MediaIds:");
CampaignManagementExampleHelper.outputArrayOflong(mediaIds);
// Get the media representations to confirm the stored dimensions
// and get the Url where you can later view or download the media.
ArrayList<MediaEnabledEntityFilter> responsiveAdFilter = new ArrayList<MediaEnabledEntityFilter>();
responsiveAdFilter.add(MediaEnabledEntityFilter.RESPONSIVE_AD);
outputStatusMessage("-----\nGetMediaMetaDataByAccountId:");
ArrayOfMediaMetaData getResponsiveAdMediaMetaData = CampaignManagementExampleHelper.getMediaMetaDataByAccountId(
responsiveAdFilter,
null).getMediaMetaData();
outputStatusMessage("MediaMetaData:");
CampaignManagementExampleHelper.outputArrayOfMediaMetaData(getResponsiveAdMediaMetaData);
ArrayList<MediaEnabledEntityFilter> imageAdExtensionFilter = new ArrayList<MediaEnabledEntityFilter>();
imageAdExtensionFilter.add(MediaEnabledEntityFilter.IMAGE_AD_EXTENSION);
outputStatusMessage("-----\nGetMediaMetaDataByAccountId:");
ArrayOfMediaMetaData getImageAdExtensionMediaMetaData = CampaignManagementExampleHelper.getMediaMetaDataByAccountId(
imageAdExtensionFilter,
null).getMediaMetaData();
outputStatusMessage("MediaMetaData:");
CampaignManagementExampleHelper.outputArrayOfMediaMetaData(getImageAdExtensionMediaMetaData);
outputStatusMessage("-----\nGetMediaMetaDataByIds:");
ArrayOfMediaMetaData getMediaMetaData = CampaignManagementExampleHelper.getMediaMetaDataByIds(
mediaIds).getMediaMetaData();
outputStatusMessage("MediaMetaData:");
CampaignManagementExampleHelper.outputArrayOfMediaMetaData(getMediaMetaData);
// Delete the account's media.
outputStatusMessage("-----\nDeleteMedia:");
CampaignManagementExampleHelper.deleteMedia(
authorizationData.getAccountId(),
mediaIds);
for (java.lang.Long id : mediaIds.getLongs())
{
outputStatusMessage(String.format("Deleted Media Id %s", id));
}
}
catch (Exception ex) {
String faultXml = ExampleExceptionHelper.getBingAdsExceptionFaultXml(ex, System.out);
outputStatusMessage(faultXml);
String message = ExampleExceptionHelper.handleBingAdsSDKException(ex, System.out);
outputStatusMessage(message);
}
}
// Get image media that can be managed with the Campaign Management API.
static Image getImageMedia(
java.lang.String mediaType,
java.lang.String imageFileName) throws UnsupportedEncodingException, IOException
{
Image image = new Image();
image.setData(getBmpBase64String(imageFileName));
image.setMediaType(mediaType);
image.setType("Image");
return image;
}
// Get the image media as base64 string.
static java.lang.String getBmpBase64String(
java.lang.String imageFileName) throws UnsupportedEncodingException, IOException
{
File fi = new File(imageFileName);
byte[] imageBytes = Files.readAllBytes(fi.toPath());
java.lang.String base64String = new java.lang.String(Base64.getEncoder().encode(imageBytes), "UTF-8");
return base64String;
}
}
<?php
namespace Microsoft\BingAds\Samples\V13;
// For more information about installing and using the Bing Ads PHP SDK,
// see https://go.microsoft.com/fwlink/?linkid=838593.
require_once __DIR__ . "/../vendor/autoload.php";
include __DIR__ . "/AuthHelper.php";
include __DIR__ . "/OutputHelper.php";
include __DIR__ . "/CampaignManagementExampleHelper.php";
use SoapVar;
use SoapFault;
use Exception;
// Specify the Microsoft\BingAds\V13\CampaignManagement classes that will be used.
use Microsoft\BingAds\V13\CampaignManagement\Image;
use Microsoft\BingAds\V13\CampaignManagement\MediaEnabledEntityFilter;
// Specify the Microsoft\BingAds\Auth classes that will be used.
use Microsoft\BingAds\Auth\ServiceClient;
use Microsoft\BingAds\Auth\ServiceClientType;
// Specify the Microsoft\BingAds\Samples classes that will be used.
use Microsoft\BingAds\Samples\V13\AuthHelper;
use Microsoft\BingAds\Samples\V13\CampaignManagementExampleHelper;
// To run this example you'll need to provide your own images.
// For required aspect ratios and recommended dimensions please see
// Image remarks at https://go.microsoft.com/fwlink/?linkid=872754.
$mediaFilePath = "c:\\dev\\media\\";
$responsiveAdMediaFileName = "imageresponsivead1200x628.png";
$imageAdExtensionMediaFileName = "imageadextension300x200.png";
try
{
// Authenticate user credentials and set the account ID for the sample.
AuthHelper::Authenticate();
$responsiveAdImageMedia = GetImageMedia(
"Image191x100",
$mediaFilePath . $responsiveAdMediaFileName
);
$imageAdExtensionMedia = GetImageMedia(
"Image15x10",
$mediaFilePath . $imageAdExtensionMediaFileName
);
$addMedia = array();
$addMedia[] = $responsiveAdImageMedia;
$addMedia[] = $imageAdExtensionMedia;
print("Ready to upload image media:\r\n");
CampaignManagementExampleHelper::OutputArrayOfMedia($addMedia);
print("-----\r\nAddMedia:\r\n");
$mediaIds = CampaignManagementExampleHelper::AddMedia(
$GLOBALS['AuthorizationData']->AccountId,
$addMedia
)->MediaIds;
print("MediaIds:\r\n");
CampaignManagementExampleHelper::OutputArrayOfLong($mediaIds);
// Get the media representations to confirm the stored dimensions
// and get the Url where you can later view or download the media.
print("-----\r\nGetMediaMetaDataByAccountId:\r\n");
$mediaMetaData =CampaignManagementExampleHelper::GetMediaMetaDataByAccountId(
MediaEnabledEntityFilter::ResponsiveAd,
null
)->MediaMetaData;
print("MediaMetaData:\r\n");
CampaignManagementExampleHelper::OutputArrayOfMediaMetaData($mediaMetaData);
print("-----\r\nGetMediaMetaDataByAccountId:\r\n");
$mediaMetaData = CampaignManagementExampleHelper::GetMediaMetaDataByAccountId(
MediaEnabledEntityFilter::ImageAdExtension,
null
)->MediaMetaData;
print("MediaMetaData:\r\n");
CampaignManagementExampleHelper::OutputArrayOfMediaMetaData($mediaMetaData);
print("-----\r\nGetMediaMetaDataByIds:\r\n");
$mediaMetaData = CampaignManagementExampleHelper::GetMediaMetaDataByIds(
$mediaIds
)->MediaMetaData;
print("MediaMetaData:\r\n");
CampaignManagementExampleHelper::OutputArrayOfMediaMetaData($mediaMetaData);
// Delete the account's media.
print("-----\r\nDeleteMedia:\r\n");
CampaignManagementExampleHelper::DeleteMedia(
$GLOBALS['AuthorizationData']->AccountId,
$mediaIds
);
foreach ($mediaIds->long as $id)
{
printf("Deleted Media Id %s\r\n", $id);
}
}
catch (SoapFault $e)
{
printf("-----\r\nFault Code: %s\r\nFault String: %s\r\nFault Detail: \r\n", $e->faultcode, $e->faultstring);
var_dump($e->detail);
print "-----\r\nLast SOAP request/response:\r\n";
print $GLOBALS['Proxy']->GetWsdl() . "\r\n";
print $GLOBALS['Proxy']->GetService()->__getLastRequest()."\r\n";
print $GLOBALS['Proxy']->GetService()->__getLastResponse()."\r\n";
}
catch (Exception $e)
{
// Ignore fault exceptions that we already caught.
if ($e->getPrevious())
{ ; }
else
{
print $e->getCode()." ".$e->getMessage()."\n\n";
print $e->getTraceAsString()."\n\n";
}
}
function GetImageMedia(
$mediaType,
$imageFileName){
$image = new Image();
$image->Data = GetBase64ImageData($imageFileName);
$image->MediaType = $mediaType;
$image->Type = "Image";
$encodedImage = new SoapVar(
$image,
SOAP_ENC_OBJECT,
'Image',
$GLOBALS['CampaignManagementProxy']->GetNamespace()
);
return $encodedImage;
}
function GetBase64ImageData($imageFileName){
$imageData = file_get_contents($imageFileName);
$base64ImageData = base64_encode($imageData);
return $base64ImageData;
}
import base64
from auth_helper import *
from campaignmanagement_example_helper import *
# You must provide credentials in auth_helper.py.
# To run this example you'll need to provide your own images.
# For required aspect ratios and recommended dimensions please see
# Image remarks at https://go.microsoft.com/fwlink/?linkid=872754.
MEDIA_FILE_PATH = "c:\dev\media\\"
RESPONSIVE_AD_MEDIA_FILE_NAME = "imageresponsivead1200x628.png"
IMAGE_AD_EXTENSION_MEDIA_FILE_NAME = "imageadextension300x200.png"
def main(authorization_data):
try:
responsive_ad_image_media = get_image_media(
"Image191x100",
MEDIA_FILE_PATH + RESPONSIVE_AD_MEDIA_FILE_NAME)
image_ad_extension_media = get_image_media(
"Image15x10",
MEDIA_FILE_PATH + IMAGE_AD_EXTENSION_MEDIA_FILE_NAME)
add_media = {
'Media':
[
responsive_ad_image_media,
image_ad_extension_media
]
}
output_status_message("Ready to upload image media:")
output_array_of_media(add_media)
output_status_message("-----\nAddMedia:")
media_ids = campaign_service.AddMedia(
AccountId=authorization_data.account_id,
Media=add_media)
output_status_message("MediaIds:")
output_array_of_long(media_ids)
# Get the media representations to confirm the stored dimensions
# and get the Url where you can later view or download the media.
output_status_message("-----\nGetMediaMetaDataByAccountId:")
get_responsive_ad_mediametadata = campaign_service.GetMediaMetaDataByAccountId(
MediaEnabledEntities='ResponsiveAd',
PageInfo=None)
output_status_message("MediaMetaData:")
output_array_of_mediametadata(get_responsive_ad_mediametadata)
output_status_message("-----\nGetMediaMetaDataByAccountId:")
get_image_ad_extension_mediametadata = campaign_service.GetMediaMetaDataByAccountId(
MediaEnabledEntities='ImageAdExtension',
PageInfo=None)
output_status_message("MediaMetaData:")
output_array_of_mediametadata(get_image_ad_extension_mediametadata)
output_status_message("-----\nGetMediaMetaDataByIds:")
get_mediametadata = campaign_service.GetMediaMetaDataByIds(
MediaIds=media_ids).MediaMetaData
output_status_message("MediaMetaData:")
output_array_of_mediametadata(get_mediametadata)
# Delete the account's media.
output_status_message("-----\nDeleteMedia:")
delete_media_response = campaign_service.DeleteMedia(
authorization_data.account_id,
media_ids)
for id in media_ids['long']:
output_status_message("Deleted Media Id {0}".format(id))
except WebFault as ex:
output_webfault_errors(ex)
except Exception as ex:
output_status_message(ex)
def get_image_media(
media_type,
image_file_name):
image = campaign_service.factory.create('Image')
image.Data = get_bmp_base64_string(image_file_name)
image.MediaType = media_type
image.Type = "Image"
return image
def get_bmp_base64_string(image_file_name):
image = open(image_file_name, 'rb')
image_bytes = image.read()
base64_string = base64.b64encode(image_bytes)
return base64_string
# Main execution
if __name__ == '__main__':
print("Loading the web service client proxies...")
authorization_data=AuthorizationData(
account_id=None,
customer_id=None,
developer_token=DEVELOPER_TOKEN,
authentication=None,
)
campaign_service=ServiceClient(
service='CampaignManagementService',
version=13,
authorization_data=authorization_data,
environment=ENVIRONMENT,
)
authenticate(authorization_data)
main(authorization_data)