Cutting AI Prompt Tokens by Turning Text into Images with .NET

Sending text to an AI model as an image sounds like it should cost more. The application has to render the text, encode a PNG and send a much larger payload over the network. Yet for the right kind of prompt, the model may consume substantially fewer input tokens than it would if it received the same material as ordinary text.
Some published experiments have reported savings of up to 70% for particular models and workloads. That figure needs to be treated as a measured result rather than a general promise, but the underlying technique is real. A dense image can sometimes carry far more readable text per billed model token than the provider's text tokeniser can.
I first came across the practical version of this idea while watching ThePrimeagen discuss pxpipe. I then read DeepSeek's paper on contexts optical compression, which explores the idea more formally. That led me to build and publicly release PromptRaster, an open-source .NET library for selectively representing large text inputs as image context in applications built around Microsoft.Extensions.AI.
https://www.youtube.com/watch?v=Bbt8cEyzsTk&t=333s
PromptRaster doesn't claim to have invented optical context compression. The broad idea already existed, and pxpipe had demonstrated a clever TypeScript implementation for AI coding workflows. PromptRaster takes that idea in a different direction, in process, policy controlled integration for .NET applications.
Why text and images can have different token costs
When text is sent normally, it passes through the model's text tokeniser. The tokeniser breaks it into units representing words, fragments of words, punctuation and whitespace. Source code, JSON, logs and repetitive structured content can produce a surprisingly large number of tokens because their symbols and formatting don't always pack as efficiently as ordinary text.
An image follows a different route. A multimodal model's vision encoder divides or resizes the image according to the provider's image processing rules and converts the result into visual tokens. Its cost is commonly driven by dimensions, detail level, tiling and model specific rules. It isn't necessarily proportional to every character visible in the image. That creates an opportunity. If thousands of characters can be rendered legibly into an image whose dimensions result in relatively few visual tokens, the model may receive a compressed visual representation of the same context.
This doesn't mean a PNG file is smaller than the original string. It will often be much larger in bytes. Network size, storage size and model token count are separate measurements. Optical context compression is concerned with the representation inside the model request, not conventional file compression.
Think of the jumbled text memes
There are memes in which the letters inside each word have been rearranged while the first and last letters remain in place. The wording is visibly wrong, but most people can still read the sentence at close to normal speed because the brain recognises shapes, context and likely patterns rather than carefully decoding every character in isolation.
A multimodal model reading a dense page of text has a loose similarity to that experience. It doesn't need a separate language token for every visible fragment before it can use the material. Its vision system builds a compressed representation from pixels, shapes, layout and surrounding context, then the language model reasons over that representation. The analogy is useful, but it shouldn't be taken literally. A vision language model isn't reading in the same biological way as a person, and the image channel isn't a lossless text codec. The important connection is pattern recognition. Both a person reading jumbled text and a model reading rendered context can recover meaning from an imperfect representation because context helps to resolve what is seen.
That also explains the main limitation. We can understand the meaning of a jumbled sentence while misreading a particular letter. A model may understand an imaged log or design document while getting one digit, slash or identifier wrong. Optical compression can preserve meaning without preserving every character.
What DeepSeek demonstrated
DeepSeek's 2025 paper, DeepSeek-OCR: Contexts Optical Compression, investigated whether visual input could act as an efficient compression medium for long text. Its DeepEncoder produces a restricted number of vision tokens from a document image, which a language decoder then uses to reconstruct or understand the content.
In its experiments, DeepSeek reported 97% OCR precision while the number of text tokens remained below ten times the number of vision tokens. At a compression ratio of 20, accuracy fell to roughly 60%. The paper describes token reductions in the range of 7 to 20 times across different historical context stages. Those are interesting research results, but they aren't evidence that every commercial multimodal API will make an application ten times cheaper. DeepSeek evaluated its own architecture, datasets and token allocations. An application calling Azure OpenAI, OpenAI, Anthropic or another provider is subject to that provider's vision encoding, model capability and pricing.
The wider lesson is more durable, text doesn't have to enter a language model only through a text tokeniser. A vision encoder provides another route, and for dense, approximate context that route can be more token-efficient.
The loose idea already existed in TypeScript
pxpipe applies this idea as a TypeScript proxy and library. It sits between an AI coding client and a supported model API, identifies bulky parts of the request, renders them as PNG pages and forwards the rewritten request to the multimodal model.
Its primary targets include system prompts, tool documentation, older conversation history, large tool results, logs and JSON. Current instructions and recent turns can remain as text. According to the project's published measurements, dense real-world content packed roughly 3.1 characters per image token compared with around one character per text token in the traffic it tested. It reports workload specific end-to-end savings of approximately 59% to 70% at the prices used for those tests.
Thats a smart use of an existing model capability. It also proves that the concept doesn't require a new foundation model. If an existing multimodal model can read dense screenshots reliably enough, request context can be rendered before it reaches the API.
However, a local proxy aimed at coding agents isn't always the right integration point for a production .NET system. An ASP.NET Core API, worker, Azure Function or document processing pipeline may already use dependency injection and Microsoft.Extensions.AI. Adding a transparent HTTP proxy can obscure which content has changed representation and make application-specific policy harder to enforce.
How PromptRaster is different
PromptRaster is a public, open-source .NET native visual context encoder released under the MIT licence. It runs inside the application and makes no outbound network calls itself. The application continues to communicate with its chosen provider through IChatClient, while PromptRaster decides whether explicitly selected content should remain text or become one or more PNG pages.
The distinction is control. PromptRaster doesn't automatically convert every large string in the request. A caller marks content as eligible using RasterTextContent or AddRasterText, and a rasterisation policy makes the final decision. Ordinary TextContent stays untouched.
This allows a request to keep its live instructions in text while moving bulky supporting information onto the image channel. A short instruction such as "summarise the background material and identify the main risks" needs exact interpretation, so it remains text. The long reference document can be considered for rasterisation because the model mainly needs its meaning.
The core renderer is provider neutral and uses SkiaSharp to generate deterministic PNG pages. Provider access remains behind Microsoft.Extensions.AI. PromptRaster can therefore sit in an application using Azure OpenAI, OpenAI or another multimodal provider without its core package taking a dependency on any one of them.
It also has conservative failure behaviour. Unsupported models, rejected content, rendering errors and uneconomical page density can fall back to the original text. Applications that require stricter handling can enable strict mode and receive an exception instead.
Adding PromptRaster to a .NET application
Install the core package and the Microsoft.Extensions.AI integration:
dotnet add package PromptRaster
dotnet add package PromptRaster.MicrosoftExtensionsAI
The following example registers PromptRaster, adds it to an existing IChatClient pipeline and marks only the background document as rasterisable:
using Microsoft.Extensions.AI;
using Microsoft.Extensions.DependencyInjection;
using PromptRaster;
using PromptRaster.MicrosoftExtensionsAI;
var services = new ServiceCollection()
.AddPromptRasterMicrosoftExtensionsAI(options =>
{
options.MinimumTextLength = 4_000;
options.FallbackToText = true;
})
.BuildServiceProvider();
var rasterizer = services.GetRequiredService<IPromptRasterizer>();
IChatClient client = providerClient
.AsBuilder()
.UsePromptRaster(rasterizer, options =>
{
options.MinimumCharacterCount = 4_000;
options.FallbackToText = true;
options.Provider = AiProvider.AzureOpenAI;
})
.Build();
var message = new ChatMessage(
ChatRole.User,
"Summarise the attached background material.");
message.Contents.Add(
new TextContent("Focus on risks and unresolved questions."));
message.AddRasterText(backgroundDocument);
ChatResponse response = await client.GetResponseAsync(
[message],
cancellationToken: stopToken);
The instruction stays as TextContent. If policy approves the background material, PromptRaster replaces that marked portion with one or more DataContent objects using the image/png media type. If it rejects the conversion, the original string is sent as text. This fits naturally into ASP.NET Core, worker services, Azure Functions and other hosts that already construct an IChatClient through dependency injection. No proxy process has to be started, routed or monitored.
Policy matters more than rendering
Turning a string into a PNG is the easy part. Choosing which strings may safely be turned into images is the important part. PromptRaster's default policy checks the text length, model profile, content classification, exact content heuristics, page limit and rendered density. Unknown models fall back to text unless an application supplies an appropriate profile. The application can replace IRasterisationPolicy or IExactContentDetector when its domain has stronger requirements.
Large documentation, descriptive schemas, historical logs and older supporting material can be reasonable candidates. Secrets, access tokens, hashes, file paths, exact financial figures and identifiers generally aren't. If one character changes the result, the value belongs in the text channel or should be obtained through a deterministic tool. Structured data also needs judgement. A large JSON document may rasterise efficiently when the task is to explain its broad structure, but it is a poor candidate when the model must reproduce exact property values. The same input can therefore be suitable for one task and unsafe for another.
Where PromptRaster can help .NET systems
A document processing application may attach a long policy manual as context while asking the model to classify an incoming document. A support system may include older case notes so the model can produce a summary. An engineering assistant may need a large block of logs to identify a likely cause rather than quote every line exactly. These workloads share two useful properties, the context is large, and semantic understanding matters more than byte-perfect recovery. They are also common in .NET systems that already call multimodal models through Azure OpenAI or another IChatClient implementation.
PromptRaster can cache rasterised pages through IPromptRasterCache, using stable keys for identical content and render settings. It also exposes structured logging and OpenTelemetry compatible activity and metric instrumentation without writing the prompt text or image bytes into logs. Those features are important when the technique moves from an experiment into an application request path.
Why 70% must remain an "up to" figure
The saving depends on several variables , the text tokeniser, image dimensions, density, provider vision token rules, model accuracy, caching and current prices. A dense page of code may perform very differently from loosely spaced prose. A provider can also change its image pricing or token accounting independently of its text pricing. Prompt caching complicates the comparison further. Repeated text may already be cheap when a provider serves cached input tokens at a discount. Converting that same stable block to an image could reduce the raw token count while producing a smaller financial benefit than expected. A fair benchmark must compare equivalent cache states.
Quality belongs in the calculation too. Saving 70% while subtly corrupting an account number isn't an optimisation. A useful evaluation measures token usage, actual cost, latency and task accuracy against the original text request. It should use the exact provider and model that the production application will use.
PromptRaster intentionally doesn't publish a universal savings number today. Its repository includes the benchmark methodology, while reproducible evaluation fixtures and model specific results remain on the roadmap. The pxpipe figures show what can be possible in a favourable workload. They shouldn't be relabelled as a PromptRaster guarantee.
A second input channel for large context
The most interesting part of this technique isn't that it turns text into a picture. It is that a multimodal model gives an application two ways to deliver language: directly through text tokens or indirectly through a visual representation. Text remains the right format for current instructions, exact values and anything security sensitive. Images can be useful for bulky background material where the model needs to recognise patterns and meaning. The jumbled text meme captures the intuition, perfect character-by-character recovery isn't always required to understand what a passage says.
pxpipe showed how effectively that idea could be applied to AI coding traffic in TypeScript. PromptRaster brings the technique into .NET applications through explicit content selection, dependency injection, policy, fallback behaviour, caching and Microsoft.Extensions.AI middleware.
There won't be a 70% saving on every request. For some prompts, there may be no saving at all. But when a .NET application repeatedly sends large, stable and semantically read only context to a capable multimodal model, optical context compression is now a practical option worth measuring.




