Image to Image in Ruby
Overview
Convert images between formats and resize, crop, or rotate them with the PDFCrowd Ruby client. The client handles communication with the API, while conversions run on PDFCrowd's servers.
Installation
Install the Ruby client with gem, or see other installation options.
gem install pdfcrowd
Quick Start
The examples below use your API credentials. The examples use demo credentials, so you can try the API before getting your own API key. Update the input URLs and filenames as needed.
Convert an Image URL
Convert a PNG image to JPEG and save it locally as logo.jpg:
require 'pdfcrowd' client = Pdfcrowd::ImageToImageClient.new('demo', 'demo') client.setOutputFormat('jpg') client.convertUrlToFile('https://your-server.com/logo.png', 'logo.jpg')
The URL must return the image itself and be reachable from PDFCrowd's servers.
The client raises Pdfcrowd::Error on conversion or validation errors.
See Handle Errors.
Convert an Image File
Convert logo.png to JPEG and save it locally as logo.jpg:
require 'pdfcrowd' client = Pdfcrowd::ImageToImageClient.new('demo', 'demo') client.setOutputFormat('jpg') client.convertFileToFile('logo.png', 'logo.jpg')
Configure a Conversion
Authentication
Pass your PDFCrowd username and API key to
ImageToImageClient.
Find your credentials on the API Keys page.
Choose an Input
The source image format is detected automatically. Each conversion accepts one image.
| Input | Method |
|---|---|
| URL | convertUrlToFile() |
| Local file | convertFileToFile() |
| Bytes in memory | convertRawDataToFile() |
| Readable binary stream | convertStreamToFile() |
For a local image or a URL on localhost, upload the file, bytes, or an open binary stream.
Remote URLs must be reachable from PDFCrowd's servers.
Send Image Bytes
Read logo.png as bytes, convert it to JPEG, and save logo.jpg:
require 'pdfcrowd' client = Pdfcrowd::ImageToImageClient.new('demo', 'demo') image = File.binread('logo.png') client.setOutputFormat('jpg') client.convertRawDataToFile(image, 'logo.jpg')
Add Conversion Settings
Set conversion options on the client before calling a conversion method.
For example, client.setOutputFormat("jpg") selects JPEG output.
Common settings are listed below. See the method reference for all available options or browse Ruby examples.
Image operations change the source image; canvas settings control the output area and image placement.
| Purpose | Methods |
|---|---|
| Resize or rotate | setResize(), setRotate() |
| Crop or remove solid-color borders | setCropArea(), setRemoveBorders() |
| Image resolution for layout | setDpi() |
| Image format | setOutputFormat() |
| Canvas dimensions and margins | setCanvasSize(), setCanvasDimensions(), setMargins(), setOrientation() |
| Image placement and background | setPrintCanvasMode(), setPosition(), setCanvasBackgroundColor() |
With an explicit canvas size, use setPrintCanvasMode() with "fit" to preserve the aspect ratio and fit the image inside the margins.
The "stretch" mode fills the area and can distort the image. The default mode does not scale the image to fit and can crop it.
Without an explicit size, margins add a border around the image.
Handle the Result
Choose an Output
The examples select JPEG. Use setOutputFormat() to choose PNG, WebP, or another supported format. The client defaults to PNG; match the filename extension to the selected format.
The methods below use URL input; local files, bytes, and input streams have corresponding methods.
| Output | Method |
|---|---|
| Local file | convertUrlToFile() |
| String in memory | convertUrl() |
| Writable IO object | convertUrlToStream() |
Ruby strings can hold binary data. This example converts an image,
receives the result as a string and saves it as logo.jpg:
require 'pdfcrowd' client = Pdfcrowd::ImageToImageClient.new('demo', 'demo') client.setOutputFormat('jpg') result = client.convertUrl('https://your-server.com/logo.png') File.binwrite('logo.jpg', result)
When serving the result from a web application, use Content-Type: image/jpeg for these examples, or the content type corresponding to your selected format.
Handle Errors
The client raises a Pdfcrowd::Error
exception on conversion or validation errors.
This example converts an image and logs any PDFCrowd error, including its
HTTP status and reason code:
require 'pdfcrowd' require 'logger' logger = Logger.new($stderr) client = Pdfcrowd::ImageToImageClient.new('demo', 'demo') begin client.setOutputFormat('jpg') client.convertUrlToFile('https://your-server.com/logo.png', 'logo.jpg') rescue Pdfcrowd::Error => error logger.error("PDFCrowd: #{error}") logger.error("Status: #{error.getStatusCode}; reason: #{error.getReasonCode}") raise end
Local Ruby errors, such as a failure to read an input file or write the output, may need separate handling.
Pdfcrowd::Error provides these methods:
| Method | Returns |
|---|---|
getStatusCode() | The HTTP status code, when available. |
getReasonCode() | The reason code identifying the specific error, or -1 if unavailable. |
getMessage() | The error message. |
getDocumentationLink() | A link to relevant documentation, when available. |
error.to_s returns the complete error, including available status and reason codes.
Common Status Codes
| Status | What it means | What to do |
|---|---|---|
400 | Invalid input, settings, or conversion failure | Read the reason code and correct the input or settings. |
401 | Missing credentials or an inactive license | Check your username, API key, and license status. |
403 | Suspended service or no credits remaining | Check your account and available credits. |
413 | Upload exceeds the 300 MB limit | Reduce the upload size. |
429 | Request rate limit reached | Wait and reduce the rate of new requests. |
430 | Concurrent request limit reached | Allow active requests to finish before starting more. |
503 | Temporary network issue | Check your retry policy before submitting another request. |
See all status and reason codes for specific explanations and Limits and Retries for retry behavior.
Read Conversion Information
This information is available after a conversion and describes the client's last conversion.
| Method | Use |
|---|---|
getJobId() | Identify the conversion in logs and support requests. |
getDebugLogUrl() | The URL of the conversion debug log when logging is enabled. |
getOutputSize() | Read the JPEG size in bytes. |
getConsumedCreditCount() | Read the credits consumed by the conversion. |
getRemainingCreditCount() | Read the remaining credit count reported with the conversion. |
Limits and Retries
Request rate and concurrency limits depend on your license. Control how quickly
your application submits conversions and how many it runs at once. A
429 response concerns request rate; a 430 response
concerns requests already in progress. The maximum upload size is 300 MB.
The Ruby client automatically retries a request once when it receives HTTP
502 or 503. Use
setRetryCount()
to change that count, or set it to 0 to disable automatic retries.
Account for these retries when adding an application-level retry policy.
Troubleshooting
Inspect a Conversion
This example converts an image with debug logging enabled and records the debug log URL when available. Use the input and settings from the conversion you are investigating.
require 'pdfcrowd' require 'logger' logger = Logger.new($stderr) client = Pdfcrowd::ImageToImageClient.new('demo', 'demo') begin client.setOutputFormat('jpg') client.setDebugLog(true) client.convertUrlToFile('https://your-server.com/logo.png', 'logo.jpg') rescue Pdfcrowd::Error => error logger.error("PDFCrowd: #{error}") logger.error("Status: #{error.getStatusCode}; reason: #{error.getReasonCode}") raise ensure debug_log_url = client.getDebugLogUrl() logger.info("Debug log: #{debug_log_url}") unless debug_log_url.to_s.empty? end
The debug log contains conversion settings and processing details. You can also find logs in your conversion history. A local or connection failure may occur before a conversion log is available.
Common Problems
| Problem | Check |
|---|---|
| The image cannot be loaded | Check that the URL returns an image, rather than HTML or a login page, and is reachable from PDFCrowd's servers. For local files, check the path and read permissions. |
| The image is distorted or cropped | Check dimensions, crop settings and margins. Use "fit" with setPrintCanvasMode() when setting an explicit output size. |
| The result looks blurry | Check the source image's pixel dimensions and how much it is enlarged. Increasing DPI cannot recover missing detail. |
| Transparency is lost | JPEG does not support transparency. Select PNG and check whether the canvas background adds an opaque color. |
For help, contact support and include any available diagnostics, the client version, and enough detail to reproduce the problem.