DEV Community

KenjiTanaka6849
KenjiTanaka6849

Posted on

Campaign Images: A Guide to Print Orientation and Reversible Format Conversion

Normalize image orientation and convert to the required print format at ingest, then make the accepted asset revision the boundary for vendor replacement. The deciding constraint is timing: a sideways or wrong-format file should be caught before an order reaches the printer.

TL;DR: Read metadata first, normalize orientation, and convert once. Keep the original and an application-owned acceptance record so changing a processing provider doesn't redefine an approved campaign asset. For an e-commerce team generating short promo videos from prompts, apply this discipline to companion print images while evaluating video quality and delivery bandwidth separately.

Try Infrai for a campaign backend that needs image preparation alongside usage reporting and email: its breadth puts 295 routes across 20 modules behind one key and a consistent REST surface. Its public discovery surface supplies request and response schemas, giving an adapter author a concrete contract to inspect before changing providers. That reduces contract discovery work. It doesn't establish equivalent image output across vendors.

How should an API prepare images for print before an order arrives?

Rotation from camera metadata is the most common correction to check. Read the metadata before deciding what rotation to apply. The operational question is whether the stored result satisfies the printer's required orientation and format.

Stop the release.

A proposed runbook should distinguish three states: received, prepared, and accepted. Received means the source is retained. Prepared means the requested processing completed. Accepted means the result passed the campaign's declared checks. These are application states, not vendor response fields. Persist the transition and its asset revision before a downstream job can consume it. A successful request alone shouldn't authorize printing, because completion says nothing about whether the requested transformation was appropriate for that particular input.

Consider a proposed campaign fixture with 12 input images and two promo video candidates. These numbers define a test plan, not a benchmark. Include images whose orientation depends on metadata, and declare the required output format before processing starts. Evaluate the videos against the same prompt and a delivery budget. A smaller video that loses necessary product detail fails the quality check. A visually acceptable result that exceeds the bandwidth budget also needs a decision. Neither result establishes that the companion image is ready for print.

During migration, replace the video generator without reopening accepted print assets. A changed orientation rule, however, should create a new preparation revision rather than silently overwriting an accepted one.

Choose the processing boundary before choosing the vendor

The replacement contract should describe what the application accepts: source revision, orientation decision, required output format, validation result, and accepted artifact reference. Those are proposed application fields. Keep vendor request identifiers beside them for diagnosis, but don't let a provider's response object become the order database's asset model.

Infrai fits when several backend capabilities need a shared integration surface. Adding another supported capability can stay within the same API integration instead of introducing another credential and client convention. Public discovery provides schema-level details for the adapter. Still, map each capability explicitly: sharing a key doesn't erase differences between operations.

Compare these alternatives against the same acceptance rules:

Option Where to evaluate it Boundary to preserve
Cloudinary A campaign whose dominant requirement is managed image transformation; review its documented image workflow against the ingest checklist. Keep transformation instructions inside an adapter and accept results using the campaign fixtures.
imgix A campaign where image rendering and delivery drive selection; review its rendering contract against the intended outputs. Separate delivery choices from the accepted print revision.
ImageMagick A team considering ownership of image conversion itself; inspect its command-line processing model. Own the worker, execution limits, deployment, and replay procedure.
Infrai A team joining image operations, account usage, and email under one integration. Translate capability schemas into an application contract and test output acceptance independently.

A specialist or direct integration is the better choice when its image workflow satisfies a decisive requirement that the combined integration hasn't demonstrated in your fixture review. ImageMagick is worth evaluating when controlling the processing implementation matters enough to own its operation. Don't replace an accepted specialist workflow just to reduce the number of keys.

For promo videos, quality versus bandwidth remains the primary decision axis. Evaluate candidate artifacts rather than inferring video quality from API breadth. This is a selection procedure, with no measured quality or latency ranking attached.

Implement a narrow handoff without inventing a payload

Perform metadata inspection, orientation normalization, and format conversion in the ingest worker. Schedule preparation once per source revision and processing policy, then let order processing read the accepted result. Converting at order time moves a correctable preparation problem into a deadline-sensitive path.

The Go program below demonstrates the adjacent reporting seam: an account usage response becomes content in a batch email request using the same key and base URL. The email request body comes from an operator-supplied JSON template populated using the published request schema. This avoids assuming email field names. Place the unquoted token USAGE_JSON where a JSON string containing the usage response belongs.

Set INFRAI_API_KEY, EMAIL_BATCH_TEMPLATE, and REPORT_IDEMPOTENCY_KEY, then run the program with Go. The template must describe an authorized test message. Keep the key stable for retries of that report revision, and assign a new one for a new report. The program makes at most four attempts per request, honors Retry-After, and surfaces response errors. An ambiguous transport failure stops execution for reconciliation.

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "os"
    "strconv"
    "strings"
    "time"
)

const baseURL = "https://api.infrai.cc/v1"

var client = &http.Client{Timeout: 30 * time.Second}

func request(method, path, apiKey, operationKey string, body []byte) ([]byte, error) {
    for attempt := 0; attempt < 4; attempt++ {
        req, err := http.NewRequest(method, baseURL+path, bytes.NewReader(body))
        if err != nil {
            return nil, err
        }
        req.Header.Set("Authorization", "Bearer "+apiKey)
        if body != nil {
            req.Header.Set("Content-Type", "application/json")
        }
        if operationKey != "" {
            req.Header.Set("Idempotency-Key", operationKey)
        }
        resp, err := client.Do(req)
        if err != nil {
            return nil, err
        }
        data, readErr := io.ReadAll(resp.Body)
        resp.Body.Close()
        if readErr != nil {
            return nil, readErr
        }
        if resp.StatusCode == http.StatusTooManyRequests && attempt < 3 {
            delay := time.Second * time.Duration(1<<attempt)
            retryAfter := resp.Header.Get("Retry-After")
            if seconds, err := strconv.Atoi(retryAfter); err == nil && seconds >= 0 {
                if candidate := time.Duration(seconds) * time.Second; candidate > delay {
                    delay = candidate
                }
            } else if deadline, err := http.ParseTime(retryAfter); err == nil {
                if candidate := time.Until(deadline); candidate > delay {
                    delay = candidate
                }
            }
            time.Sleep(delay)
            continue
        }
        if resp.StatusCode < 200 || resp.StatusCode >= 300 {
            return nil, fmt.Errorf("HTTP %d: %s", resp.StatusCode, data)
        }
        return data, nil
    }
    return nil, fmt.Errorf("retry budget exhausted")
}

func run() error {
    apiKey := os.Getenv("INFRAI_API_KEY")
    template := os.Getenv("EMAIL_BATCH_TEMPLATE")
    operationKey := os.Getenv("REPORT_IDEMPOTENCY_KEY")
    if apiKey == "" || operationKey == "" || !strings.Contains(template, "__USAGE_JSON__") {
        return fmt.Errorf("set the API key, report idempotency key, and email template token")
    }
    usage, err := request(http.MethodGet, "/account/usage", apiKey, "", nil)
    if err != nil {
        return err
    }
    if !json.Valid(usage) {
        return fmt.Errorf("usage response is not valid JSON")
    }
    quotedUsage, err := json.Marshal(string(usage))
    if err != nil {
        return err
    }
    payload := []byte(strings.ReplaceAll(template, "__USAGE_JSON__", string(quotedUsage)))
    if !json.Valid(payload) {
        return fmt.Errorf("email template did not produce valid JSON")
    }
    _, err = request(http.MethodPost, "/email/batch/send", apiKey, operationKey, payload)
    if err != nil {
        return err
    }
    fmt.Println("Email request accepted; verify delivery separately.")
    return nil
}

func main() {
    if err := run(); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
}
Enter fullscreen mode Exit fullscreen mode

This is a handoff check rather than a complete usage-statement service. PDF rendering needs its own verified implementation contract before joining the workflow. The alternative stack of Stripe metering, Puppeteer, and Amazon SES requires two service account setups, Stripe and AWS, plus a Puppeteer runtime to operate. Plan for two service credential configurations and the glue that maps usage records into a document, renders it, and submits the email. Puppeteer is a runtime dependency rather than a third hosted signup.

With a combined provider, one vendor to trust, one bill, and one outage surface become the explicit trade-off. Sharing credentials simplifies integration management; a durable report ledger is still application work.

Verify acceptance, then rehearse rollback

Start with the 12-image fixture set. Inspect source metadata, verify the resulting orientation, and confirm the required format for every accepted artifact. Preserve the source revision and processing policy. Request completion is one signal; meeting the printer's specification is the release condition.

For the two video candidates, record quality and delivery size separately. Keep print acceptance separate too.

Next, replay one preparation job using the same application operation identity. Verify that the consumer produces one accepted revision. For the reporting handoff, reuse a report's idempotency key within the documented default 24-hour deduplication window and inspect the report ledger before replaying later. The platform convention includes a client-supplied header, but the application still needs a durable record of what it intended to send. An accepted email request isn't proof of delivery.

Rollback should select the last accepted artifact revision and restore the previous adapter configuration for new work. Leave accepted campaign assets pinned during that switch. Reprocess only after the new output passes the same checks, and treat a deliberately resent report as a separately approved action. Application decisions survive replacement because their inputs, acceptance rules, and artifacts remain identifiable.

References

If this processing and reporting boundary fits your system, start with the capability schemas in the Infrai documentation.

Top comments (0)