### Install AWS SDK for S3 Source: https://tinify.com/developers/reference/nodejs Install the AWS SDK for JavaScript to interact with S3-compatible storage providers. This is a prerequisite for the S3 storage example. ```bash npm install --save @aws-sdk/client-s3 ``` -------------------------------- ### Install AWS SDK for S3 Source: https://tinify.com/developers/reference/ruby Install the AWS SDK for Ruby to interact with S3-compatible storage providers. This is a prerequisite for the S3 store example. ```bash gem install aws-sdk-s3 ``` -------------------------------- ### Install Boto3 for S3 Storage Source: https://tinify.com/developers/reference/python Install the boto3 library, which is required for interacting with S3-compatible storage providers. ```bash pip install boto3 ``` -------------------------------- ### Python Client Installation Source: https://tinify.com/developers/reference/python Install the Tinify Python client library using pip. ```APIDOC ## Installation You can use the Python client by installing the Python package: ``` pip install --upgrade tinify ``` ``` -------------------------------- ### Verify curl Installation Source: https://tinify.com/developers/reference/http Check if curl is installed on your system. This is a prerequisite for following the command-line examples. ```bash curl --version ``` -------------------------------- ### Installation Source: https://tinify.com/developers/reference/nodejs Install the Tinify Node.js client package using npm. ```APIDOC ## Installation You can use the Node.js client by installing the npm package and adding it to your application’s dependencies: ``` npm install --save tinify ``` ``` -------------------------------- ### Install AWS SDK for S3 Source: https://tinify.com/developers/reference/dotnet Install the AWSSDK.S3 NuGet package to interact with S3-compatible storage providers. ```powershell Install-Package AWSSDK.S3 ``` -------------------------------- ### Install Azure Storage Blob Package Source: https://tinify.com/developers/reference/php Install the Microsoft Azure Storage Blob package using Composer to enable saving images to Azure. ```bash composer require Microsoft/azure-storage-blob ``` -------------------------------- ### Install AWS SDK for PHP Source: https://tinify.com/developers/reference/php Install the AWS SDK for PHP using Composer if you plan to save images to S3-compatible storage. ```bash composer require aws/aws-sdk-php ``` -------------------------------- ### Install Tinify Python Client Source: https://tinify.com/developers/reference/python Install the Tinify Python package using pip. This command upgrades the package if it is already installed. ```bash pip install --upgrade tinify ``` -------------------------------- ### Install Tinify Node.js Client Source: https://tinify.com/developers/reference/nodejs Install the Tinify npm package to use the client library in your Node.js application. ```bash npm install --save tinify ``` -------------------------------- ### HTTP Response Example Source: https://tinify.com/developers/reference/http A successful HTTP response indicating creation. ```http HTTP/1.1 201 Created ``` -------------------------------- ### Install Azure Storage Blob Package Source: https://tinify.com/developers/reference/nodejs Install the Azure Storage Blob package for Node.js to enable saving images to Microsoft Azure Blob Storage. ```bash npm install --save @azure/storage-blob ``` -------------------------------- ### Install Tinify NuGet Package Source: https://tinify.com/developers/reference/dotnet Install the Tinify client library using the NuGet Package Manager. This package supports .NET Standard 1.4 and above. ```powershell Install-Package Tinify ``` -------------------------------- ### Install Azure Storage Package Source: https://tinify.com/developers/reference/dotnet Add the Azure.Storage.Blobs NuGet package to your project to enable interaction with Microsoft Azure Blob Storage. ```bash dotnet add package Azure.Storage.Blobs ``` -------------------------------- ### Manually Install Tinify PHP Client Source: https://tinify.com/developers/reference/php Include the Tinify PHP client files manually if not using Composer. ```php require_once("lib/Tinify/Exception.php"); require_once("lib/Tinify/ResultMeta.php"); require_once("lib/Tinify/Result.php"); require_once("lib/Tinify/Source.php"); require_once("lib/Tinify/Client.php"); require_once("lib/Tinify.php"); ``` -------------------------------- ### Install Azure Storage Blob Package Source: https://tinify.com/developers/reference/ruby Install the Azure Storage Blob package for Ruby to enable saving images to Microsoft Azure Blob Storage. This is a necessary step before using the Azure storage functionality. ```bash gem install azure-storage-blob ``` -------------------------------- ### Install Tinify PHP Client with Composer Source: https://tinify.com/developers/reference/php Use Composer to add the Tinify PHP client to your project dependencies. ```bash composer require tinify/tinify ``` -------------------------------- ### HTTP Response for File Upload Source: https://tinify.com/developers/reference This is an example HTTP response after a successful image upload and compression request. ```http HTTP/1.1 201 Created { "input": { "size": 207565, "type": "image/jpeg" } } ``` -------------------------------- ### HTTP Response Example - Unauthorized Source: https://tinify.com/developers/reference/http This is an example of an HTTP response indicating an unauthorized request due to invalid credentials. ```http HTTP/1.1 401 Unauthorized { "error": "Unauthorized", "message": "Credentials are invalid" } ``` -------------------------------- ### Download and Save Compressed Image using curl Source: https://tinify.com/developers/reference/http Example using curl to download the compressed image and save it to a file. The `open` command is used to view the saved image. ```bash curl https://api.tinify.com/output/2xnsp7jn34e5 \ --user api:YOUR_API_KEY \ --output optimized.jpg open optimized.jpg ``` -------------------------------- ### Install Tinify Ruby Gem Source: https://tinify.com/developers/reference/ruby Add this line to your application's Gemfile to include the Tinify Ruby client. ```ruby gem "tinify" ``` -------------------------------- ### Example GCS Storage using cURL Source: https://tinify.com/developers/reference/http Use this cURL command to save a compressed image to Google Cloud Storage, including optional headers for browser caching. ```bash curl https://api.tinify.com/output/2xnsp7jn34e5 \ --user api:YOUR_API_KEY \ --dump-header /dev/stdout --silent \ --header "Content-Type: application/json" \ --data '{ \ "store" : { \ "service": "gcs", \ "gcp_access_token": "EXAMPLE_TOKEN_Ag_0HvsglgriGU_EXAMPLE_TOKEN", \ "headers": { \ "Cache-Control": "public, max-age=31536000" \ }, \ "path": "example-bucket/my-images/optimized.jpg" \ } \ }' ``` -------------------------------- ### HTTP Response for URL Upload Source: https://tinify.com/developers/reference This is an example HTTP response after a successful image upload request using a URL. It indicates the output details. ```http HTTP/1.1 201 Created { "output": { "size": 30734, "type": "image/png" } } ``` -------------------------------- ### Compress Image via File Upload using curl Source: https://tinify.com/developers/reference/http Example using curl to upload a local image file for compression. Ensure you replace YOUR_API_KEY with your actual key. The --dump-header flag shows the response headers. ```bash curl https://api.tinify.com/shrink \ --user api:YOUR_API_KEY \ --data-binary @unoptimized.jpg \ --dump-header /dev/stdout ``` -------------------------------- ### Upload Optimized Image to Azure Blob Storage Source: https://tinify.com/developers/reference/java This Java example demonstrates connecting to an Azure blob container using a connection string and uploading an image optimized by TinyPNG. Ensure you have your Azure storage connection string and container name. ```java String connectStr = ""; BlobServiceClient blobServiceClient = new BlobServiceClientBuilder().connectionString(connectStr).buildClient(); String containerName = ""; BlobContainerClient containerClient = blobServiceClient.getBlobContainerClient(containerName); String fileToUpload = "optimized.png" Source source = Tinify.fromUrl("https://tinypng.com/images/panda-happy.png"); source.toFile("optimized.png"); blobClient.uploadFromFile(fileToUpload); ``` -------------------------------- ### API Key Authentication Source: https://tinify.com/developers/reference/dotnet To use the Tinify API, you must authenticate with your API key. This example shows how to set the API key in the client. ```APIDOC ## Authentication ### Description To use the API you must provide your API key. You can get an API key by registering with your name and email address. Always keep your API key secret! ### Code Example ```csharp using TinifyAPI; class Example { static void Main() { Tinify.Key = "YOUR_API_KEY"; } } ``` ``` -------------------------------- ### Convert Image to WebP and PNG Source: https://tinify.com/developers/reference/python Converts an image to multiple formats, returning the smallest version. The 'tinify' library must be installed. The result's extension is dynamically determined. ```python source = tinify.from_file("panda-sticker.jpg") converted = source.convert(type=["image/webp","image/png"]) extension = converted.result().extension converted.to_file("panda-sticker." + extension) ``` -------------------------------- ### Compress Image from Buffer (Python) Source: https://tinify.com/developers/reference/python Compress image data from a buffer (string with binary data) and get the compressed image data back using the Python client. ```APIDOC You can also upload an image from a buffer (a string with binary) and get the compressed image data. ```python with open("unoptimized.jpg", 'rb') as source: source_data = source.read() result_data = tinify.from_buffer(source_data).to_buffer() ``` ``` -------------------------------- ### Save Image to S3 Compatible Storage Source: https://tinify.com/developers/reference/nodejs Store an optimized image to an S3-compatible storage provider. This example requires the AWS SDK and proper configuration of endpoint, region, and credentials. ```javascript let source = tinify.fromUrl("https://tinypng.com/images/panda-happy.png"); let optimisedImage = source.toBuffer(); const s3Client = new s3.S3({ endpoint: "https://YOUR-ENDPOINT.com", region: "REGION", credentials: { accessKeyId: "KEY_EXAMPLE", secretAccessKey: "YOUR_SECRET_KEY", }, }); s3Client.send(new s3.PutObjectCommand({ Bucket: "bucket-name", Key: "file-name.png", Body: optimisedImage, ContentType: "image/png", })); ``` -------------------------------- ### HTTP Request for Downloading Compressed Image Source: https://tinify.com/developers/reference/http This GET request is used to retrieve the compressed image. The URL is obtained from the `Location` header of the compression response. ```http GET /output/2xnsp7jn34e5 HTTP/1.1 ``` -------------------------------- ### Resize Image using Curl Source: https://tinify.com/developers/reference/http Use curl to send a resize request to the Tinify API. This example demonstrates how to specify resize dimensions and save the output to a file. ```bash curl https://api.tinify.com/output/2xnsp7jn34e5 \ --user api:YOUR_API_KEY \ --header "Content-Type: application/json" \ --data '{ "resize": { "method": "fit", "width": 150, "height": 100 } }' \ --dump-header /dev/stdout --silent \ --output thumbnail.jpg ``` -------------------------------- ### Saving to S3 Compatible Storage Source: https://tinify.com/developers/reference/python While the TinyPNG API doesn't have a direct integration for S3-compatible storage, you can save images using the provided Python example with `boto3`. ```APIDOC ## Saving to S3 compatible storage Although the TinyPNG API does not offer an integrated solution for saving the images directly to S3 compatible storage providers other than Amazon, you can still save your images using the example for your chosen development language. The S3 API is used by storage providers like Digital Ocean Spaces, Backblaze, G-Core Storage, Wasabi, Century Link Object Storage, Filebase and many others. If you don’t have the AWS SDK installed already, you can add it using the following command: ```bash pip install boto3 ``` ### Store example ```python source = tinify.from_url("https://tinypng.com/images/panda-happy.png") buff = source.to_buffer() session = boto3.session.Session() client = session.client('s3',region_name='REGION',endpoint_url='https://YOUR-ENDPOINT.com',aws_access_key_id='KEY_EXAMPLE',aws_secret_access_key='YOUR_SECRET_KEY') client.put_object(Bucket='bucket-name',Key='file-name.png',Body=buff,ContentType= "image/png") ``` The detailed documentation on how to use the S3 API can be found here. ``` -------------------------------- ### Resize Image using Fit Method Source: https://tinify.com/developers/reference/python Resizes an image to fit within specified dimensions using the 'fit' method. Ensure the 'tinify' library is installed and configured. ```python source = tinify.from_file("large.jpg") resized = source.resize( method="fit", width=150, height=100 ) resized.to_file("thumbnail.jpg") ``` -------------------------------- ### Compress Image via URL Upload using curl Source: https://tinify.com/developers/reference/http Example using curl to compress an image from a URL. This method requires setting the Content-Type header to application/json and providing the image URL within the JSON data. ```bash curl https://api.tinify.com/shrink \ --user api:YOUR_API_KEY \ --header "Content-Type: application/json" \ --data '{"source": {"url": "https://tinypng.com/images/panda-happy.png"} }' \ --dump-header /dev/stdout ``` -------------------------------- ### Include Composer Autoloader Source: https://tinify.com/developers/reference/php Require Composer's autoloader to use the installed Tinify PHP client. ```php require_once("vendor/autoload.php"); ``` -------------------------------- ### Handling Transparency with Background Color Source: https://tinify.com/developers/reference/nodejs Demonstrates how to convert an image with transparency to a format that does not support it (like JPEG) by specifying a background color. ```APIDOC ## `convert` and `transform` with Background Color ### Description This method allows you to convert an image to a different format and specify a background color to replace transparency, especially useful when converting to formats like JPEG that do not support transparency. ### Method `source.convert({type: "image/jpeg"}).transform({background: "#000000"})` ### Parameters #### Request Body - **`type`** (string or array of strings) - Required - The desired image type(s) (e.g., `"image/webp"`, `["image/webp","image/png"]`, or `"*/*"`). - **`background`** (string) - Required when converting transparent images to non-transparent formats - Specifies the background color to replace transparency. Supported values are hex codes (e.g., `"#000000"`) or the strings `"white"` or `"black"`. ### Request Example ```javascript const source = tinify.fromFile("panda-sticker.png"); const converted = source.convert({type:"image/jpeg"}).transform({background:"#000000"}); converted.toFile("panda-sticker.jpg"); ``` ### Response #### Success Response Returns the converted and transformed image file. #### Response Example (File output to `panda-sticker.jpg`) ``` -------------------------------- ### Authentication Source: https://tinify.com/developers/reference/nodejs Set your API key for authentication and optionally configure a proxy server. ```APIDOC ## Authentication To use the API you must provide your API key. You can get an API key by registering with your name and email address. Always keep your API key secret! ``` const tinify = require("tinify"); tinify.key = "YOUR_API_KEY"; ``` All requests must be made over an encrypted HTTPS connection. You can instruct the API client to make all requests over an HTTP proxy. Set the URL of your proxy server, which can optionally include credentials. ``` tinify.proxy = "http://user:pass@192.168.0.1:8080"; ``` ``` -------------------------------- ### Compress Image from Buffer Source: https://tinify.com/developers/reference/nodejs Compress image data from a buffer and get the compressed data as a buffer. Handles potential read errors. ```javascript const fs = require("fs"); fs.readFile("unoptimized.jpg", function(err, sourceData) { if (err) throw err; tinify.fromBuffer(sourceData).toBuffer(function(err, resultData) { if (err) throw err; // ... }); }); ``` -------------------------------- ### Example GCS Request Body Source: https://tinify.com/developers/reference/http This JSON body instructs the Tinify API to store a compressed image directly to Google Cloud Storage. ```json { "store" : { "service": "gcs", "gcp_access_token": "YOUR_GCP_TOKEN_HERE", "path": "example-bucket/my-images/optimized.jpg" } } ``` -------------------------------- ### Compress Image from Local File Source: https://tinify.com/developers/reference/dotnet Compress an image from a local file and save the optimized version to another file. This method uses async I/O. ```csharp var source = Tinify.FromFile("unoptimized.webp"); await source.ToFile("optimized.webp"); ``` -------------------------------- ### Convert Image with Solid Background using cURL Source: https://tinify.com/developers/reference/http This cURL command demonstrates how to convert a transparent image to JPEG and set a black background. Ensure you replace YOUR_API_KEY with your actual Tinify API key. ```bash curl https://api.tinify.com/output/2xnsp7jn34e5 \ --user api:YOUR_API_KEY \ --header "Content-Type: application/json" \ --data '{ "convert" : {"type": "image/jpeg"}, "transform": {"background": "#000000"}}' \ --dump-header /dev/stdout \ --output panda-sticker.jpg ``` -------------------------------- ### Convert Transparent Image to JPEG with Solid Background Source: https://tinify.com/developers/reference/python Use this when converting a transparent image to a format that does not support transparency, like JPEG. Specify a background color to replace transparency. ```python source = tinify.from_file("panda-sticker.png") converted = source.convert(type="image/jpeg").transform(background="#000000") converted.to_file("panda-sticker.jpg") ``` -------------------------------- ### Download compressed image with preserved metadata using curl Source: https://tinify.com/developers/reference/http This `curl` command demonstrates how to download a compressed image while preserving copyright and creation metadata. Replace `YOUR_API_KEY` with your actual Tinify API key. The output is saved to `optimized-copyright.jpg`. ```bash curl https://api.tinify.com/output/2xnsp7jn34e5 \ --user api:YOUR_API_KEY \ --header "Content-Type: application/json" \ --data '{ "preserve": ["copyright", "creation"] }' \ --dump-header /dev/stdout \ --output optimized-copyright.jpg ``` -------------------------------- ### Get Compression Count - Ruby Source: https://tinify.com/developers/reference/ruby Retrieve the number of compressions made this month. This can be done after validating your API key or after making at least one compression request. ```ruby compressions_this_month = Tinify.compression_count ``` -------------------------------- ### Configure Tinify Proxy Source: https://tinify.com/developers/reference/python Set up an HTTP proxy for the Tinify API client if required. The proxy URL can include credentials. ```python tinify.proxy = "http://user:pass@192.168.0.1:8080" ``` -------------------------------- ### Get Tinify Compression Count Source: https://tinify.com/developers/reference/nodejs Retrieve the number of compressions made this month. This count is available after validating the API key or after at least one compression request. ```javascript let compressionsThisMonth = tinify.compressionCount; ``` -------------------------------- ### Compress Image from Buffer Source: https://tinify.com/developers/reference/php Compress image data from a buffer (string) and return the optimized image data as a buffer. ```php $sourceData = file_get_contents("unoptimized.jpg"); $resultData = \Tinify\fromBuffer($sourceData)->toBuffer(); ``` -------------------------------- ### Compress Image from File Source: https://tinify.com/developers/reference/php Compress an image from a local file and save the optimized result to another file. ```php $source = \Tinify\fromFile("unoptimized.webp"); $source->toFile("optimized.webp"); ``` -------------------------------- ### Get Compression Count Source: https://tinify.com/developers/reference/java Retrieves the number of compressions made in the current month. This method is available after validating your API key or after making at least one compression request. ```APIDOC ## Get Compression Count ### Description Retrieves the number of compressions made in the current month. This method is available after validating your API key or after making at least one compression request. ### Method ```java int compressionsThisMonth = Tinify.compressionCount(); ``` ### Language Java ``` -------------------------------- ### Resizing Images Source: https://tinify.com/developers/reference/dotnet Use the API to create resized versions of your uploaded images. The resized images will be optimally compressed with a nice and crisp appearance. Resizing counts as one additional compression. ```APIDOC ## Resizing Images Use the API to create resized versions of your uploaded images. By letting the API handle resizing you avoid having to write such code yourself and you will only have to upload your image once. The resized images will be optimally compressed with a nice and crisp appearance. You can also take advantage of intelligent cropping to create thumbnails that focus on the most visually important areas of your image. Resizing counts as one additional compression. For example, if you upload a single image and retrieve the optimized version plus 2 resized versions this will count as 3 compressions in total. To resize an image, call the `resize` method on an image source: ```csharp var source = Tinify.FromFile("large.jpg"); var resized = source.Resize(new { method = "fit", width = 150, height = 100 }); await resized.ToFile("thumbnail.jpg"); ``` The `method` describes the way your image will be resized. The following methods are available: ### scale Scales the image down proportionally. You must provide either a target width or a height, but not both. The scaled image will have exactly the provided width or height. ### fit Scales the image down proportionally so that it fits within the given dimensions. You must provide both a width and a height. The scaled image will not exceed either of these dimensions. ### cover Scales the image proportionally and crops it if necessary so that the result has exactly the given dimensions. You must provide both a width and a height. Which parts of the image are cropped away is determined automatically. An intelligent algorithm determines the most important areas of your image. ### thumb A more advanced implementation of cover that also detects **cut out images** with plain backgrounds. The image is scaled down to the width and height you provide. If an image is detected with a free standing object it will **add more background space** where necessary or **crop** the unimportant parts. This feature is new and we’d love to hear your feedback! If the target dimensions are larger than the original dimensions, the image will not be scaled up. Scaling up is prevented in order to protect the quality of your images. ``` -------------------------------- ### Get Monthly Compression Count Source: https://tinify.com/developers/reference/java Retrieve the number of compressions made this month. This method is available after validating your API key or after making at least one compression request. ```java int compressionsThisMonth = Tinify.compressionCount(); ``` -------------------------------- ### Convert Image to Multiple Formats Source: https://tinify.com/developers/reference/java Convert an image to PNG and WebP, returning the smallest version. Ensure the Tinify library is initialized. ```java Source source = Tinify.fromFile("panda-sticker.jpg"); Result converted = source.convert(new Options().with("type",new String[]{"image/png","image/webp"} )).result(); String extension = converted.extension(); converted.toFile("panda-sticker." + extension); ``` -------------------------------- ### Convert image with transparency to JPEG with a background color Source: https://tinify.com/developers/reference/ruby Demonstrates how to convert a PNG image with transparency to JPEG format, specifying a background color to replace the transparent areas. ```APIDOC ## Convert Image with Transparency ### Description Convert an image with a transparent background to a format that does not support transparency (like JPEG) by specifying a background color. ### Method `convert` and `transform` methods are used. ### Parameters #### `convert` method options: - `type`: Desired image type (e.g., `"image/jpeg"`, `"image/webp"`, `"image/png"`, or `"*/*"`). #### `transform` method options: - `background`: Specifies the background color to replace transparency. Can be a hex value (e.g., `"#000000"`) or the strings `"white"` or `"black"`. ### Request Example ```ruby source = Tinify.from_file("panda-sticker.png") converted = source.convert(type: "image/jpeg").transform(background: "#000000") converted.to_file("panda-sticker.jpg") ``` ### Response - The converted image file is saved to the specified path. ``` -------------------------------- ### Convert Image using Curl Source: https://tinify.com/developers/reference/http This curl command shows how to convert an image to WebP format. The output is saved to a specified file name. ```bash curl https://api.tinify.com/output/2xnsp7jn34e5 \ --user api:YOUR_API_KEY \ --header "Content-Type: application/json" \ --data '{ "convert": { "type": "image/webp"} }' \ --dump-header /dev/stdout \ --output panda-sticker.webp ``` -------------------------------- ### Upload Image to Azure Blob Storage Source: https://tinify.com/developers/reference/dotnet Connect to Azure Blob Storage using a connection string and upload an image optimized by Tinify. Ensure you have the Azure Storage SDK installed. ```csharp var connectStr = ""; var blobServiceClient = BlobServiceClient.fromConnectionString(); var containerName = ""; var containerClient = await blobServiceClient.CreateBlobContainerAsync(containerName); var fileToUpload = "optimized.png" var source = Tinify.FromUrl("https://tinypng.com/images/panda-happy.png"); await source.ToFile(fileToUpload); var blobClient = containerClient.GetBlobClient(fileName); await blobClient.UploadAsync(fileToUpload, true); ``` -------------------------------- ### HTTP Response for Downloading Compressed Image Source: https://tinify.com/developers/reference/http A successful download request returns a 200 OK status. The actual image data is in the response body. ```http HTTP/1.1 200 OK ``` -------------------------------- ### Compress Image from URL Source: https://tinify.com/developers/reference/php Compress an image directly from a URL and save the optimized result to a local file. ```php $source = \Tinify\fromUrl("https://tinypng.com/images/panda-happy.png"); $source->toFile("optimized.png"); ``` -------------------------------- ### Example S3 Access Policy Source: https://tinify.com/developers/reference/dotnet This JSON policy grants the necessary permissions for the Tinify API to upload objects to your S3 bucket. It allows `PutObject` and `PutObjectAcl` actions on specified resources. ```json { "Statement": { "Effect": "Allow", "Action": [ "s3:PutObject", "s3:PutObjectAcl" ], "Resource": [ "arn:aws:s3:::example-bucket/*" ] } } ``` -------------------------------- ### Upload Optimized Image to Azure Blob Storage Source: https://tinify.com/developers/reference/python Connects to Azure Blob Storage using a connection string and uploads an image optimized by Tinify. Ensure you have the Azure SDK for Python installed. ```python connect_str = blob_service_client = BlobServiceClient.from_connection_string(connect_str) containerName = "" container_client = blob_service_client.get_container_client(containerName) fileToUpload = "optimized.png" source = tinify.from_url("https://tinypng.com/images/panda-happy.png") source.to_file(fileToUpload) with open(fileToUpload, "rb") as data: blob_client.upload_blob(data) ``` -------------------------------- ### Upload Optimized Image to Azure Blob Storage Source: https://tinify.com/developers/reference/nodejs Connect to Azure Blob Storage using a connection string and upload an image optimized by Tinify. Ensure you have the Azure SDK for JavaScript installed. ```javascript const connectionString = ""; const blobServiceClient = BlobServiceClient.fromConnectionString(connectionString); const containerName = ""; const containerClient = blobServiceClient.getContainerClient(containerName); const source = tinify.fromUrl("https://tinypng.com/images/panda-happy.png"); const buff = await source.toBuffer(); const optimizedImage = "tiny-optimized.png"; const blockBlobClient = containerClient.getBlockBlobClient(optimizedImage); const uploadBlobResponse = await blockBlobClient.upload(buff, buff.length); ``` -------------------------------- ### Convert Transparent Image to JPEG with Black Background Source: https://tinify.com/developers/reference/ruby Use this to convert a PNG image with transparency to JPEG format, replacing the transparent background with black. Ensure the 'Tinify' gem is installed and configured. ```ruby source = Tinify.from_file("panda-sticker.png") converted = source.convert(type: "image/jpeg").transform(background: "#000000") converted.to_file("panda-sticker.jpg") ``` -------------------------------- ### Get Compression Count (Python) Source: https://tinify.com/developers/reference/python Retrieve the number of compressions made this month using the Tinify API client. This requires prior API key validation or at least one compression request. ```python compressions_this_month = tinify.compression_count ``` -------------------------------- ### Compress Image from File (Python) Source: https://tinify.com/developers/reference/python Compress an image from a local file and save the optimized version to another file using the Python client. ```APIDOC ## Compressing Images You can upload any AVIF, WebP, JPEG or PNG image to the Tinify API to compress it. We will automatically detect the type of image and optimise with the TinyPNG or TinyJPG engine accordingly. Compression will start as soon as you upload a file or provide the URL to the image. You can choose a local file as the source and write it to another file. ```python source = tinify.from_file("unoptimized.webp") source.to_file("optimized.webp") ``` ``` -------------------------------- ### Upload Image for Shrinking Source: https://tinify.com/developers/reference/http Uploads an image to the Tinify service for compression. This is the first step before applying further operations. ```APIDOC ## POST /shrink ### Description Uploads an original image to the Tinify service for compression. This endpoint is typically used as the initial step before other operations. ### Method POST ### Endpoint /shrink ### Request Body - **Binary Data** - Required - The image file to be uploaded. ### Request Example (Refer to the `curl` example in the source for a practical request.) ### Response #### Success Response (201 Created) - **output** (object) - Contains information about the processed output. - **size** (integer) - The size of the output image in bytes. - **type** (string) - The MIME type of the output image. #### Response Example ```json { "output": { "size": 45974, "type": "image/jpeg" } } ``` #### Error Handling (Error handling details not provided in the source text.) ``` -------------------------------- ### Upload Image to Azure Blob Storage with Tinify Source: https://tinify.com/developers/reference/ruby Connect to Azure Blob Storage using a connection string and upload an image optimized by Tinify. Ensure you have the Azure Storage SDK for Ruby installed. ```ruby connectionString = ''; client = Azure::Storage::Blob::BlobService.create_from_connection_string(connectionString) containerName = '' container = client.create_container(containerName) fileToUpload = "optimized.png" source = Tinify.from_url("https://tinypng.com/images/panda-happy.png") source.to_file(fileToUpload) content = ::File.open(fileToUpload, 'rb') { |file| file.read } client.create_block_blob(container.name, 'image-blob', content) ``` -------------------------------- ### Get Tinify Compression Count Source: https://tinify.com/developers/reference/dotnet Retrieve the number of compressions made this month. This count is automatically tracked by the API client and can be accessed after validating the API key or making at least one compression request. ```csharp var compressionsThisMonth = Tinify.CompressionCount; ``` -------------------------------- ### Convert Image with Solid Background Source: https://tinify.com/developers/reference/http Use this request to convert a transparent image to a specified format and fill its background with a solid color. The background property is required when converting to formats that do not support transparency. ```json POST /output/2xnsp7jn34e5 HTTP/1.1 { "convert" : { "type": "image/jpeg" }, "transform": { "background": "#000000" } } ``` -------------------------------- ### Download compressed image with preserved metadata Source: https://tinify.com/developers/reference/http Use this request to download the compressed image and preserve specific metadata. The URL should be from the `Location` header of a previous compression step. Supported metadata includes 'copyright' and 'creation'. ```HTTP POST /output/2xnsp7jn34e5 HTTP/1.1 { "preserve": ["copyright", "creation"] } ``` -------------------------------- ### Save Optimized Image to S3 Compatible Storage Source: https://tinify.com/developers/reference/php Save optimized images to S3-compatible storage by first getting the image data as a buffer and then using the AWS S3 client to put the object. Configure your endpoint, region, and credentials correctly. ```php $source = \Tinify\fromUrl("https://tinypng.com/images/panda-happy.png"); $resultData = $source->toBuffer(); $client = new Aws\S3\S3Client([ 'version' => 'latest', 'region' => 'REGION', 'endpoint' => 'https://YOUR-ENDPOINT.com', 'credentials' => [ 'key' => "KEY_EXAMPLE", 'secret' => "YOUR_SECRET_KEY", ], ]); $client->putObject([ 'Bucket' => 'bucket-name', 'Key' => 'file-name.png', 'Body' => $resultData, 'ContentType' => 'image/png' ]); ``` -------------------------------- ### Compress Image from Buffer to Buffer Source: https://tinify.com/developers/reference/ruby Compress image data read from a buffer (string) and return the optimized data as a buffer. ```ruby source_data = File.read("unoptimized.jpg") result_data = Tinify.from_buffer(source_data).to_buffer ``` -------------------------------- ### Compress Image from Buffer Source: https://tinify.com/developers/reference/dotnet Compress image data provided as a byte array (buffer) and retrieve the optimized image data as a byte array. This is useful for in-memory operations. ```csharp var sourceData = File.ReadAllBytes("unoptimized.jpg"); var resultData = await Tinify.FromBuffer(sourceData).ToBuffer(); ``` -------------------------------- ### HTTP Response for Image Compression Source: https://tinify.com/developers/reference/http A successful compression request returns a 201 Created status with details about the input image size and type. ```http HTTP/1.1 201 Created { "input": { "size": 207565, "type": "image/jpeg" } } ``` -------------------------------- ### Saving to Microsoft Azure Source: https://tinify.com/developers/reference/python This section outlines how to save compressed images to Microsoft Azure storage, noting that direct integration is not provided but can be achieved using the Azure Storage package. ```APIDOC ## Saving to Microsoft Azure Although the TinyPNG API does not offer an integrated solution for saving the images directly to Microsoft Azure storage, you can still save your images using the example for your chosen development language. Keep in mind you will need to install the Azure Storage package using the following command: ```bash pip install azure-storage-blob ``` ``` -------------------------------- ### Compress Image from File Source: https://tinify.com/developers/reference/python Compress an image from a local file and save the optimized version to another file. Supports various image formats like AVIF, WebP, JPEG, and PNG. ```python source = tinify.from_file("unoptimized.webp") source.to_file("optimized.webp") ``` -------------------------------- ### Save Optimized Image to S3 Compatible Storage Source: https://tinify.com/developers/reference/java This Java code snippet demonstrates how to optimize an image using TinyPNG and then upload the resulting byte array to an S3-compatible storage provider. Ensure you have the AWS SDK configured with your credentials and endpoint. ```java Source source = Tinify.fromUrl("https://tinypng.com/images/panda-happy.png"); byte[] resultData = source.toBuffer(); AWSCredentials credentials = new BasicAWSCredentials( "KEY_EXAMPLE", "YOUR_SECRET_KEY" ); AmazonS3 s3client = AmazonS3ClientBuilder .standard() .withCredentials(new AWSStaticCredentialsProvider(credentials)) .withEndpointConfiguration( new AwsClientBuilder.EndpointConfiguration("https://YOUR-ENDPOINT.com", "REGION")) .build(); ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentType("image/png"); s3client.putObject( "bucket-name", "file-name.png", resultData, metadata ); ``` -------------------------------- ### Proxy Configuration Source: https://tinify.com/developers/reference/dotnet You can configure the API client to use an HTTP proxy for all requests. This is useful for network environments that require a proxy. ```APIDOC ## Proxy Configuration ### Description You can instruct the API client to make all requests over an HTTP proxy. Set the URL of your proxy server, which can optionally include credentials. ### Code Example ```csharp Tinify.Proxy = "http://user:pass@192.168.0.1:8080"; ``` ``` -------------------------------- ### Compress Image from URL Source: https://tinify.com/developers/reference/java Compresses an image directly from a URL and saves the optimized version to a local file. Avoids the need to download the image first. ```java Source source = Tinify.fromUrl("https://tinypng.com/images/panda-happy.png"); source.toFile("optimized.png"); ``` -------------------------------- ### Convert Transparent Image to JPEG with Background Color Source: https://tinify.com/developers/reference/dotnet Use this when converting an image with transparency to a format that does not support it, like JPEG. Specify a background color to replace the transparent areas. ```csharp var source = Tinify.FromFile("panda-sticker.png"); var converted = source.Convert(new {type = "image/jpeg"}).Transform(new {background = "#000000"}) await converted.ToFile("panda-sticker.jpg"); ``` -------------------------------- ### Compress Image from URL to File Source: https://tinify.com/developers/reference/ruby Compress an image directly from a URL and save the optimized version to a local file. The API handles fetching the image. ```ruby source = Tinify.from_url("https://tinypng.com/images/panda-happy.png") source.to_file("optimized.png") ``` -------------------------------- ### Download Compressed Image with Metadata Source: https://tinify.com/developers/reference Download the compressed version of an image while preserving specific metadata like copyright and creation date. The URL is obtained from the `Location` header of a previous compression step. ```APIDOC ## POST /output/{id} ### Description Downloads the compressed image with specified metadata preserved. ### Method POST ### Endpoint /output/{id} ### Parameters #### Request Body - **preserve** (array) - Required - A list of metadata to preserve. Supported values include "copyright", "creation", and "location" (JPEG only). ### Request Example ```json { "preserve": ["copyright", "creation"] } ``` ### Response #### Success Response (200) The compressed image data is returned in the response body. #### Response Example (No specific example provided, but the response contains the compressed image.) ``` -------------------------------- ### Preserve Copyright and Creation Date Metadata Source: https://tinify.com/developers/reference/php Call the `preserve` method with metadata names like 'copyright' and 'creation' to copy this information from the source image to the compressed version. This metadata preservation does not count as an extra compression. ```php $source = \Tinify\fromFile("unoptimized.jpg"); $copyrighted = $source->preserve("copyright", "creation"); $copyrighted->toFile("optimized-copyright.jpg"); ```