Integrate with Sirv

Why build upon Sirv?

No more manual editing, optimizing or administering of your images.

Sirv provides everything you need to rapidly build fast and scalable imaging into your application.

Being a high-availability platform, Sirv delivers images in a fraction of a second at very high scale. It provides you with unlimited volume of dynamic imaging on-the-fly. Each image processing request is completed within 0.15 seconds on average. Images are then cached and subsequent requests are normally complete within 1 millisecond (0.001 seconds).

We’ll keep the servers running and monitor the performance, around-the-clock. We’ll constantly refine and optimize the delivery time. We’ll resolve issues when they arise, without any impact on the service whatsoever.

HTTP API & profiles

For fast integration, the HTTP API has everything you need. Simply by appending a query string to your URL, the image will be instantly generated with the dimensions, format, quality and style that you request. Refer to the Dynamic Imaging documentation.

For greater control, create a profile so you can change image settings in future without editing any of your code. Profiles contain image settings and are applied with a query string in the URL e.g. http://example.sirv.com/test.jpg?profile=your-profile. When profile settings are changed, all images referencing that profile are changed.

Profiles are saved as JSON files, so you can even create and edit them yourself, instead of via your Profiles page. More about profiles.

S3 API

For even greater control when integrating your app with Sirv, use the Amazon S3 interface. Sirv supports the Amazon Web Services S3 REST API, allowing you to securely upload, download, edit, move, copy and delete your files on Sirv, using v3 authentication.

Choose one of the official AWS SDKs which accelerate the building of apps to fetch images, check what files exist, upload and download as well as less common requirements such as fetching image meta data (e.g. Exif).

Some of the S3 SDKs:

The SDKs are huge time-savers if you’re building an application or interfacing closely with Sirv. Also refer to the official S3 API documentation.

The S3 endpoint is s3.sirv.com and your S3 Bucket, S3 Key and S3 Secret can be found on your My Account page.

AWS SDK for PHP

If you’re using PHP, the following instructions will help you work with the AWS SDK for PHP.

  1. Download the latest version of the AWS SDK for PHP
  2. Require the AWS SDK for PHP library:
    require 'aws_sdk/aws-autoloader.php';
    use AwsS3S3Client;
    use AwsS3ExceptionS3Exception;
  3. Define your connection parameters, shown on the My Account page.
    define('AWS_KEY', '*** S3 Key parameter ***');
    define('AWS_SECRET_KEY', '*** S3 Secret parameter ***');
    define("BUCKET", '*** S3 Bucket parameter ***');
    define('HOST', 'http://s3.sirv.com');
  4. Initialize the S3 client:
    /**
    * Create and return new S3 Client
    *
    * @param string $host usualy http://s3.sirv.com
    * @param string $aws_key your AWS Key
    * @param string $aws_secret_key your AWS SECRET KEY
    *
    * @return S3Client object
    */
    function get_s3client($host, $aws_key, $aws_secret_key) {
      return S3Client::factory(array(
        'base_url' => $host,
        'key' => $aws_key,
        'secret' => $aws_secret_key)
      );
    }
    $s3client = get_s3client(HOST, AWS_KEY, AWS_SECRET_KEY);
  5. Get a list of the objects:
    /**
    * Get information about all files in folder
    *
    * @param string $bucket Your bucket name
    * @param string $folder Folder name where need get information about files. Using format "fodler1/" or "Spin/11/"
    * @param S3Client $s3client
    * @param boolean $isIterable if True than return Iterator. By default set to false
    *
    * @return object or Iterator
    */
    function get_object_list($bucket, $folder, $s3client, $isIterable = false) {
      $command = $s3client ->
      getCommand('ListObjects', array(
        'Bucket' => BUCKET,
        'Prefix' => $folder,
      ));
      if ($isIterable) {
        return $s3client ->
        getIterator($command);
      } else {
        return $command ->
        getResult();
      }
    }
    $iterator = get_object_list(BUCKET, 'folder-name/', $s3client);
    foreach($iterator as $object) {
      echo "{$object['Key']}t{$object['Size']}t{$object['LastModified']}";
    }

Now you can perform some common actions.

Upload files to Sirv

/**
* Upload files to the Sirv cloud
*
* @param string $bucket Your bucket name
* @param string $folder Folder name where files will be uploaded. Using format "fodler1/" or "Spin/11/"
* @param S3Client $s3client
* @param Array[] $array_paths_to_files Array of file's paths that need upload on server. like "/var/www/images/image1.jpg"
*/
function upload_files($bucket, $folder, $s3client, $array_paths_to_files){
  foreach ($array_paths_to_files as $file_path) {
    $commands[] = $s3client->getCommand('PutObject', array(
      'Bucket' => $bucket,
      'Key' => $folder.basename($file_path),
      'SourceFile' => $file_path
    ));
  }
  try{
    $s3client->execute($commands);
    //or in loop
    /* foreach ($commands as $command) {
    $result = $command->getResult();
      // Do something with result
    }*/
  }catch(S3Exception $e){
    echo $e->getMessage();
  }
}
$images = array('image1.jpg','image2.jpg','image3.jpg');
upload_files(BUCKET, 'folder-name/sub-folder/', $s3client, $images);

Check if a file exists

/**
* Check if file exists on server or not
*
* @param string $bucket Your bucket name
* @param string $folder Folder name where need check file. Using format like "fodler1/" or "Spin/11/"
* @param S3Client $s3client
* @param string $filenane File name that need to check on server. Using format like "image.png"
*
* @return boolean true if file exists or false if not
*/
function isFileExists($bucket, $folder, $s3client, $filenane){
  $iter_object = get_object_list($bucket, $folder, $s3client, true);
  foreach ($iter_object as $object) {
    if ($object['Key'] === $filenane){
      return true;
    }
  }
  return false;
}
$fname = "image.jpg";
if(isFileExists(BUCKET, 'folder-name/', $s3client, $fname)) {
  // File exists
}else{
  // File does not exist
}

Create a folder

/**
* Create folder on the Sirv cloud
*
* @param string $bucket Your bucket name
* @param string $folder Folder name that need create. For example if need create folder in other folder: "other/New_folder/"
*
* @return string message if folder already exists or nothing
*/
function create_folder($bucket, $folder, $s3client){
  try{
    $result = $s3client->putObject(array(
      'Bucket' => $bucket,
      'Key' => $folder,
      'Body' => "",
    ));
    print_r($result);
  }catch(S3Exception $e){
    echo $e->getMessage();
  }
}
create_folder(BUCKET, "folder-name/new-folder-name/", $s3client);

Delete a folder

/**
* Delete all files in folder and can delete files in subfolders
*
* @param string $bucket Your bucket name
* @param string $folder Folder name where files should be deleted. Using format "fodler1/" or "Spin/11/"
* @param S3Client $s3client
* @param boolean $isRecursive True if need delete files in subfolders. By default isRecursive = false
*/
function delete_folder($bucket, $folder, $s3client, $isRecursive=false){
  $filenames = $s3client->listObjects(array(
    'Bucket' => $bucket,
    'Prefix' => $folder
  ))->getPath('Contents/*/Key');
  delete_files($bucket, $folder, $s3client, $filenames);
  if ($isRecursive){
    $prefixes = $s3client->listObjects(array(
      'Bucket' => $bucket,
      'Prefix' => $folder
    ))->getPath('CommonPrefixes/*/Prefix');
    if (count($prefixes) > 0){
      foreach ($prefixes as $prefix) {
        delete_folder($bucket, $folder.$prefix, $s3client, $isRecursive=true);
      }
    }
  }
}
delete_folder(BUCKET, 'folder-name/folder-to-delete/', $s3client, true);

Delete files

$images = array('image1.jpg','image2.jpg','image3.jpg');
delete_files(BUCKET, 'folder-name/', $s3client, $images);

AWS SDK for Java

If you’re using Java, the sample code below will help you to:

  1. List the buckets in your account
  2. List objects in a bucket with a certain prefix
  3. Create a folder

In the code, look for the references to YOUR_SIRV_S3_KEY, YOUR_SIRV_S3_SECRET and YOUR_SIRV_S3_BUCKET and replace them with your S3 credentials located on your account page.

import java.io.IOException;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.Bucket;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.ListObjectsRequest;
import com.amazonaws.services.s3.model.ObjectListing;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.model.S3ObjectSummary;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.S3ClientOptions;
public class S3Sample {
  public static void main(String[] args) throws IOException {
    AWSCredentials credentials = new BasicAWSCredentials("YOUR_SIRV_S3_KEY", "YOUR_SIRV_S3_SECRET");
    String bucketName = "YOUR_SIRV_S3_BUCKET";
    String endpoint = "https://s3.sirv.com";
    System.out.println("AccessKey: " + credentials.getAWSAccessKeyId() + " | Secret Key: " + credentials.getAWSSecretKey());
    ClientConfiguration clientConfig = new ClientConfiguration();
    clientConfig.withSignerOverride("S3SignerType");
    AmazonS3 s3 = new AmazonS3Client(credentials, clientConfig);
    s3.setEndpoint(endpoint);
    s3.setS3ClientOptions(new S3ClientOptions().withPathStyleAccess(true));
    try {
      // List the buckets
      System.out.println("Listing buckets");
      for (Bucket bucket : s3.listBuckets()) {
        System.out.println(" - " + bucket.getName());
      }
      System.out.println();
      // List objects in the bucket with some prefix
      System.out.println("Listing objects");
      ObjectListing objectListing = s3.listObjects(new ListObjectsRequest().withBucketName(bucketName)
        .withPrefix("/Photos"));
      for (S3ObjectSummary objectSummary : objectListing.getObjectSummaries()) {
        System.out.println(" - " + objectSummary.getKey() + "  " + "(size = " + objectSummary.getSize() + ")");
      }
      System.out.println();
      // Create a folder
      try {
        // create meta-data for your folder and set content-length to 0
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(0);
        // create empty content
        InputStream emptyContent = new ByteArrayInputStream(new byte[0]);
        // create a PutObjectRequest passing the folder name suffixed by /
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, "TEST/", emptyContent, metadata);
        // send request to S3 to create folder
        s3.putObject(putObjectRequest);
      } catch(Exception e) {
        e.printStackTrace();
      }
    } catch (AmazonServiceException ase) {
      System.out.println("Error Message:    " + ase.getMessage());
      System.out.println("HTTP Status Code: " + ase.getStatusCode());
      System.out.println("AWS Error Code:   " + ase.getErrorCode());
      System.out.println("Error Type:       " + ase.getErrorType());
      System.out.println("Request ID:       " + ase.getRequestId());
    } catch (AmazonClientException ace) {
      System.out.println("Error Message: " + ace.getMessage());
    }
  }
}

AWS SDK for JavaScript

Manage your images on Sirv through the browser using the AWS SDK for JavaScript.

The example HTML page below will help you get started. It will:

  1. Connect to your Sirv account.
  2. Show a form to upload files to your account.
  3. After upload, show a list of files in the root directory.

To use the script:

  1. Copy and paste the code into a new HTML file.
  2. Enter your Sirv S3 credentials into the following 3 places of the script (on lines 11, 12 and 18):
    YOUR_SIRV_S3_KEY
    YOUR_SIRV_S3_SECRET
    YOUR_SIRV_S3_BUCKET
  3. Save the HTML file and test it in your browser.
<html>
<head>
    <script src="https://sdk.amazonaws.com/js/aws-sdk-2.1.43.min.js"></script>
</head>
<body>
  <div id="results"></div>
  <input type="file" id="file-chooser" />
  <button id="upload-button">Upload to S3</button>
  <script>
    AWS.config.update({
      'accessKeyId': 'YOUR_SIRV_S3_KEY',
      'secretAccessKey': 'YOUR_SIRV_S3_SECRET',
      s3ForcePathStyle: true
    });
    var s3 = new AWS.S3({
      endpoint: new AWS.Endpoint('https://s3.sirv.com'),
      params: {
        Bucket: 'YOUR_SIRV_S3_BUCKET'
      }
    });
    var fileChooser = document.getElementById('file-chooser');
    var button = document.getElementById('upload-button');
    var results = document.getElementById('results');
    button.addEventListener('click', function () {
      var file = fileChooser.files[0];
      if (file) {
        results.innerHTML = '';
        var objKey = file.name;
        var params = {
          Key: objKey,
          ContentType: file.type,
          Body: file
        };
        s3.putObject(params, function (err, data) {
          if (err) {
            results.innerHTML = 'ERROR: ' + err;
          } else {
            listObjs();
          }
        });
      } else {
        results.innerHTML = 'Nothing to upload.';
      }
    }, false);
    function listObjs() {
      var prefix = '';
      s3.listObjects({
        Prefix: prefix
      }, function (err, data) {
        if (err) {
          results.innerHTML = 'ERROR: ' + err;
        } else {
          var objKeys = "";
          data.Contents.forEach(function (obj) {
            objKeys += obj.Key + "<br>";
          });
          results.innerHTML = objKeys;
        }
      });
    }
  // listObjs();
  </script>
</body>
</html>

AWS SDK for Ruby

Use the well documented AWS SDK for Ruby to upload and manage your images on Sirv.

The code example below will list the Sirv buckets that a user has access to (each Sirv account has one bucket). When using the script, enter your Sirv S3 credentials in place of YOUR_SIRV_S3_KEY and YOUR_SIRV_S3_SECRET:

require 'aws-sdk'
s3 = Aws::S3::Resource.new(
  :endpoint => 'https://s3.sirv.com',
  :region => 'us-east-1',
  :force_path_style => true,
  :signature_version => 's3',
  :credentials => Aws::Credentials.new(
    'YOUR_SIRV_S3_KEY',
    'YOUR_SIRV_S3_SECRET'
  )
)
s3.buckets.limit(50).each do |b|
  puts "#{b.name}"
end

Was this article helpful?