Testing the generateThumbnail call of the Azure Computer Vision API from PHP. I have been able to get it to operate, but the images being saved locally are very, very poor quality. Highly pixelated, very blurry, etc. They look nothing like the examples presented at https://www.microsoft.com/cognitive-services/en-us/computer-vision-api/documentation#Thumbnails
Is this an issue with the image processing on the server side, or possibly a degradation issue occurring locally during the file save process? I'm having trouble determining where to start on this one.
This seems to be the same follow-up question asked here:
Generate thumbnail in php, posting to Azure Computer Vision API
Source image dimensions are 542x1714. Trying to create 115x115 thumbnail.
Code at the moment. Have tried it with smartCropping set to both True and False.
$posturl = 'https://westus.api.cognitive.microsoft.com/vision/v1.0/generateThumbnail';
$posturl = add_query_arg( array( 'width' => $max_w, 'height' => $max_h, 'smartCropping' => true), $posturl);
$request = wp_remote_post( $posturl, array( 'headers' => array( 'Content-Type' => 'application/octet-stream', 'Ocp-Apim-Subscription-Key' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' ), 'body' => file_get_contents( $this->file ) ) );
if ( is_wp_error( $request ) ) {
return null;
} else {
$resized = #imagecreatefromstring( $request['body'] );
}
Related
I'm using the library tmhOAuth to post to Twitter in an app and I've already implemented uploading pictures but am having trouble implementing video upload.
This is the call I use to upload pictures and works perfectly with images.
$temp = '#upload/'.$name.';type='.$_FILES['img']['type'].';filename='.$name;
$media = $tmhOAuth->request('POST', 'https://upload.twitter.com/1.1/media/upload.json', array('media' => $temp), true, true);
So I thought it might be the same for videos but I got the error
stdClass Object ( [request] => /1.1/media/upload.json [error] => media type unrecognized. )
I believe I have to make 3 separate calls, as per the Twitter API, so I tried this
$media = $tmhOAuth->request('POST', 'https://upload.twitter.com/1.1/media/upload.json?command=INIT&media_type=video/mp4&total_bytes='.$_FILES['img']['size'], array('media' => $temp), true, true);
$media_id = json_decode($tmhOAuth->response['response'])->media_id_string;
$media = $tmhOAuth->request('POST', 'https://upload.twitter.com/1.1/media/upload.json?command=APPEND&media_id='.$media_id.'&segment_index=0', array('media' => $temp), true, true);
$media = $tmhOAuth->request('POST', 'https://upload.twitter.com/1.1/media/upload.json?command=FINALIZE&media_id='.$media_id, array('media' => $temp), true, true);
but I kept getting the same error for all 3 calls
stdClass Object ( [request] => /1.1/media/upload.json [error] => media type unrecognized. )
Can anyone provide an example as to how to upload videos to twitter? I could find no examples online and it might just not be possible.
I had the same problem. Here's how I managed to solve it.
First you set up a var containing the filesystem full path to the media you want to upload.
$media_path = '/PATH/TO/THE/file.mp4';
Then instantiate $tmhOAuth and do the 3 steps :
$tmhOAuthUpload = new tmhOAuth();
INIT:
$code = $tmhOAuthUpload->request(
'POST',
$tmhOAuthUpload->url('/1.1/media/upload.json'),
array(
"command" => "INIT",
"total_bytes" => (int)filesize($media_path),
'media_type' => 'video/mp4',
)
);
Retrieve media id returned by Twitter
$results = json_decode($tmhOAuthUpload->response['response']);
$media_id = $results->media_id_string;
APPEND: Handle video/media upload with the Append loop
$fp = fopen($media_path, 'r');
$segment_id = 0;
while (! feof($fp)) {
$chunk = fread($fp, 1048576); // 1MB per chunk for this sample
$tmhOAuthUpload->request(
'POST',
$tmhOAuthUpload->url('/1.1/media/upload.json'),
array(
"command" => "APPEND",
"media_id" => $media_id,
'media_data' => base64_encode($chunk),
"segment_index" => $segment_id
)
);
$segment_id++;
}
FINALIZE:
$tmhOAuthUpload->request(
'POST',
$tmhOAuthUpload->url('/1.1/media/upload.json'),
array(
"command" => "FINALIZE",
"media_id" => $media_id,
)
);
By then I was able to to send my tweet:
$code = $tmhOAuth->request(
'POST',
$tmhOAuthUpload->url('1.1/statuses/update'),
array(
'media_ids' => $media_id,
'status' => $text,
),
true // use auth
);
Hope that helps
I've only been able to get video uploading working with CodeBird - a different PHP library.
The Twitter API calls for video are quite different from uploading images, as you've discovered.
Uploading videos to Twitter (≤ 15MB, MP4) requires you to send them in chunks. You need to perform at least 3 calls to obtain your media_id for the video:
Send an INIT event to get a media_id draft.
Upload your chunks with APPEND events, each one up to 5MB in size.
Send a FINALIZE event to convert the draft to a ready-to-tweet media_id.
Post your tweet with video attached.
Remember, each APPEND must be 5MB or under.
If you are consistently getting "Media Type Unrecognised" errors, it might be that the video you are using is incompatible with Twitter. Can you test uploading the video via another service?
Thank you very much for that answer Pierre! I was however getting a “Not valid video” error if I tried to create the tweet too soon. The video wasn't done being processed by Twitter. In addition to Pierre's code, I needed something like this to check STATUS, after FINALIZE:
$videoCount = 0;
do
{
$tmhOAuth->request(
'GET',
$tmhOAuth->url('/1.1/media/upload.json'),
array(
"command" => "STATUS",
"media_id" => $mediaID,
)
);
$twitterResult = json_decode($tmhOAuth->response['response']);
if ($twitterResult->processing_info->state != 'succeeded')
{ sleep(5); }
$videoCount++;
}
while ($twitterResult->processing_info->state != 'succeeded' && $videoCount < 5);
Note: my variable names are different
I'm trying to request data from the virgin giving api to display my fundraising information on my blog. I'm a complete novice and have been unable to workout how such a task would be completed after reading and trying out everything I can find on the topic. This is the code I have been using in a .php file within a wordpress installation on cloud9 (I have removed the search and api key). I have also tried the code on a page on my live blog which is hosted with Bluehost. I'm not sure if I'm creating the page in the correct location or if the below code should be wrapped in some sort of function. Any help that you can provide would be much appreciated.
$url = "https://api.virginmoneygiving.com/fundraisers/v1/";
$args = array(
'headers' => array( "Content-type" => "application/json" ),
'httpversion' => 1.1,
);
$response = wp_remote_get( $url, $args );
$body = wp_remote_retrieve_body( $response );
$response_code = wp_remote_retrieve_response_code( $response );
print_r( $response_code );
echo $response;
'httpversion' takes a string...
'httpversion' => '1.1',
Read more in the source.
im using file_put_contents over FTP and it only seems to be saving half the file. I'm posting an SVG over via ajax (which the server is receiving in full) and then saving to an external server. The process only takes a few seconds so it can't be a process time issue. Has anyone else had this? regards
$options = array( 'ftp' => array( 'overwrite' => true ) );
$svgSavePath = "ftp://{$user}:{$password}#{$host}/svgs/{$id}.svg";
$stream = stream_context_create( $options );
file_put_contents( $svgSavePath, $svg, 0, $stream );
I'm trying to publish tweet on twitter with image and a link to my site
I get the following error:
{"errors": [{"code": 189, "message": ". Error creating status"}]}
I tried with twitter api:
with update.json
the tweet is published but no picture.
and
update_with_media.json
I get error
this is the code I use:
require '../tmhOAuth.php';
require '../tmhUtilities.php';
$tmhOAuth = new tmhOAuth(array(
'consumer_key' => 'xxxxxxxxxx',
'consumer_secret' => 'xxxxxxxxxxxxx',
'user_token' => 'xxxxxxxxxxxxxxxxxxxx',
'user_secret' => 'xxxxxxxxxxxxxxxxxx',
));
// we're using a hardcoded image path here. You can easily replace this with an uploaded image-see images.php example)
// 'image = "#{$_FILES['image']['tmp_name']};type={$_FILES['image'] ['type']};filename={$_FILES['image']['name']}",
$picimg="img.jpg";
$code = $tmhOAuth->request('POST', 'https://api.twitter.com/1.1/statuses/update_with_media.json',
array(
'media[]' => "#{$picimg}",
'status' => "status"
),
true, // use auth
true // multipart
);
if ($code == 200) {
tmhUtilities::pr(json_decode($tmhOAuth->response['response']));
} else {
tmhUtilities::pr($tmhOAuth->response['response']);
}
I searched a lot on google but not served me anything.
I do not understand what's going on
It was poorly cast the image url and more stuff.
I have made an example of different api in my local.
I used APIs
https://github.com/themattharris/tmhOAuth
I've also installed composer for dependencies.
installing dependencies twitter api.
Well the most important thing is:
this piece of code:
$picimg="img.jpg";
array(
'media[]' => "#{$picimg}",
'status' => "status"
)
this is wrong.
but this above is good
$image = __DIR__.DIRECTORY_SEPARATOR .'..' . DIRECTORY_SEPARATOR . 'fotos'. DIRECTORY_SEPARATOR . 'foto1.jpg';
DIRECTORY_SEPARATOR is used instead of backslash, and this is very important if not the error response would be 189
$name = basename($image);
$status = "Picture time";
$media = "#{$image};type=image/jpg;filename={$name}";
media must be represented well in this format, not only url string.
// we set the type and filename are set here as well
$params = array(
'media[]' => $media,
'status' => $status
);
This is working AMIGOS
Sorry, I can only post 2 hyperlinks so I'm going to have to remove the http : //
Background
I'm, trying to convert the code here: https://github.com/RusticiSoftware/TinCan_Prototypes/blob/92969623efebe2588fdbf723dd9f33165694970c/ClientPrototypes/StatementIssuer/StatementIssuer.java
into PHP, specifically the makeRequest function. This code posts data to a Tin Can Compliant Learner Record Store.
The current version of my PHP code is here:
tincanapi.co.uk/wiki/tincanapi.co.uk:MediaWikiTinCan
The specification for the Tin Can API which everything should conform to is here:
scorm.com/wp-content/assets/tincandocs/TinCanAPI.pdf
There is also a working java script function that Posts data in the right format here (see the XHR_request function I think):
https://github.com/RusticiSoftware/TinCan_Prototypes/blob/92969623efebe2588fdbf723dd9f33165694970c/ClientPrototypes/GolfExample_TCAPI/scripts/TCDriver.js
I don't have access to the code or server that I'm posting to, but the end result should be an output here: beta.projecttincan.com/ClientPrototypes/ReportSample/index.html
Problem
I'm trying to use Curl to POST the data as JSON in PHP. Curl is returning 'false' but no error and is not posting the data.
On the recommendation of other questions on this site, I've tried adding 'json=' to the start of the POSTFIELDS, but since the Java and JavaScript versions does have this, I'm not sure this is right.
Can anybody suggest either how I might fix this or how I might get useful errors out of curl? My backup is to output the relevant JavaScript to the user's browser, but surely PHP should be able to do this server side?
Very grateful for any help.
Andrew
At least one thing is wrong: you should not be using rawurlencode on your Authorization header value.
Consider using php streams and json_encode() and json_decode() instead. The following code works.
function fopen_request_json($data, $url)
{
$streamopt = array(
'ssl' => array(
'verify-peer' => false,
),
'http' => array(
'method' => 'POST',
'ignore_errors' => true,
'header' => array(
'Authorization: Basic VGVzdFVzZXI6cGFzc3dvcmQ=',
'Content-Type: application/json',
'Accept: application/json, */*; q=0.01',
),
'content' => json_encode($data),
),
);
$context = stream_context_create($streamopt);
$stream = fopen($url, 'rb', false, $context);
$ret = stream_get_contents($stream);
$meta = stream_get_meta_data($stream);
if ($ret) {
$ret = json_decode($ret);
}
return array($ret, $meta);
}
function make_request()
{
$url = 'https://cloud.scorm.com/ScormEngineInterface/TCAPI/public/statements';
$statements = array(
array(
'actor' => array(
'name' => array('Example Name'),
'mbox' => array('mailto:example#example.com'),
'objectType' => 'Person',
),
'verb' => 'experienced',
'object' => array(
'objectType' => 'Activity',
'id'=> 'http://www.thincanapi.co.uk/wiki/index.php?Main_Page',
'definition' => array(
'name' => array('en-US'=>'TinCanAPI.co.uk-tincanapi.co.uk'),
'description' => array('en-US'=> 'TinCanAPI.co.uk-tincanapi.co.uk'),
),
),
),
);
return fopen_request_json($statements, $url);
}
list($resp, $meta) = make_request();
var_export($resp); // Returned headers, including errors, are in $meta
We've now released an open source library specifically for PHP, it uses a similar method as the accepted answer but rounds out the rest of the library as well. See:
http://rusticisoftware.github.io/TinCanPHP/
https://github.com/RusticiSoftware/TinCanPHP