[英]How to convert image binary "string" from an API response into an image file
我從外部服務器構建了一個 API 端點,以防止在使用HubSpot 事件 HTTP API發出請求時出現 CORS 問題。
事件 API 將返回圖像/gif 作為響應。 這是 HS 事件 API 請求的示例:
https://track.hubspot.com/v1/event?_n=000000001625&_a=62515&email=testingapis@hubspot.com
這是我在 WP Rest API 中創建的 API 端點:
function hs_events_api_call( $data ) {
if ( empty( $data ) ) {
return null;
}
$token = "my-token";
$endpoint = 'https://track.hubspot.com/v1/event';
$hubId = "my-hubid";
$required['_a'] = $hubId;
$required['_n'] = $data["eventid"];
$required['email'] = $data->get_param( 'email' );
$query_string = build_query_string($required);
$args = array(
'method' => 'GET',
'headers' => array(
'Authorization' => 'Bearer ' . $token,
'Content-Type' => 'application/json'
),
);
$url = $endpoint.'?'.$query_string;
$request = wp_remote_get( esc_url_raw( $url ), $args )["body"];
if( empty( $request ) ) {
return null;
}
$response = new WP_REST_Response($request);
$response->set_status(200);
$response->header('Content-Type', 'image/gif');
return $response;
}
我創建的端點的問題是它將圖像二進制文件作為字符串返回。 具體長這樣:
"GIF89a\u0001\u0000\u0001\u0000?\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000!?\u0004\u0001\u0000\u0000\u0000\u0000,\u0000\u0000\u0000\u0000\u0001\u0000\u0001\u0000@\b\u0004\u0000\u0001\u0004\u0004\u0000;"
我如何轉換它以便輸出為圖像文件,特別是“image/gif”類型?
或者根本不可能?
顯然, file_get_contents()
解決了它:
$pixel = file_get_contents( esc_url_raw( $url ) );
header('Content-Type: image/gif');
echo $pixel;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.