Extract: Crop & Rectify
extract
Find the QR codes in an image and get a PNG of each one: cut from the source exactly as it is, or resampled so that a symbol photographed at an angle comes out square and upright.
extract
An image of each symbol
extract searches an image as read does, selects among the symbols it finds, and returns an image of each selected symbol together with its decoded content. Use it to cut the code out of a scanned document, to archive the symbol that was read, or to hand a clean, straightened symbol to another program.
// Find every QR code in a photograph and save a straightened image of each
Chilkat.JsonObject jsonIn = new Chilkat.JsonObject();
jsonIn.UpdateString("source.path", "photo.jpg");
jsonIn.UpdateString("extract.mode", "rectify");
Chilkat.JsonObject jsonOut = new Chilkat.JsonObject();
Chilkat.Formats fmt = new Chilkat.Formats();
bool success = fmt.QrCode("extract", jsonIn, jsonOut);
if (!success) {
Console.WriteLine(jsonOut.StringOf("errors[0].code") + ": " + jsonOut.StringOf("errors[0].message"));
Console.WriteLine(fmt.LastErrorText);
return;
}
// outputs[i] is the image of selected[i]
int n = jsonOut.SizeOfArray("outputs");
for (int i = 0; i < n; i++) {
jsonOut.I = i;
Chilkat.BinData png = new Chilkat.BinData();
png.AppendEncoded(jsonOut.StringOf("outputs[i].base64"), "base64");
png.WriteFile("symbol" + (i + 1) + ".png");
Console.WriteLine(jsonOut.StringOf("selected[i].text") + ": "
+ jsonOut.IntOf("outputs[i].width") + " x " + jsonOut.IntOf("outputs[i].height") + " px");
}// Find every QR code in a photograph and save a straightened image of each
CkJsonObject jsonIn;
jsonIn.UpdateString("source.path", "photo.jpg");
jsonIn.UpdateString("extract.mode", "rectify");
CkJsonObject jsonOut;
CkFormats fmt;
bool success = fmt.QrCode("extract", jsonIn, jsonOut);
if (!success) {
std::cout << jsonOut.stringOf("errors[0].code") << ": " << jsonOut.stringOf("errors[0].message") << "\r\n";
std::cout << fmt.lastErrorText() << "\r\n";
return;
}
// outputs[i] is the image of selected[i]
int n = jsonOut.SizeOfArray("outputs");
for (int i = 0; i < n; i++) {
jsonOut.put_I(i);
CkBinData png;
png.AppendEncoded(jsonOut.stringOf("outputs[i].base64"), "base64");
char path[40];
sprintf(path, "symbol%d.png", i + 1);
png.WriteFile(path);
std::cout << jsonOut.stringOf("selected[i].text") << ": ";
std::cout << jsonOut.IntOf("outputs[i].width") << " x " << jsonOut.IntOf("outputs[i].height") << " px\r\n";
}import chilkat2
# Find every QR code in a photograph and save a straightened image of each
jsonIn = chilkat2.JsonObject()
jsonIn.UpdateString("source.path", "photo.jpg")
jsonIn.UpdateString("extract.mode", "rectify")
jsonOut = chilkat2.JsonObject()
fmt = chilkat2.Formats()
success = fmt.QrCode("extract", jsonIn, jsonOut)
if not success:
print(jsonOut.StringOf("errors[0].code") + ": " + jsonOut.StringOf("errors[0].message"))
print(fmt.LastErrorText)
exit()
# outputs[i] is the image of selected[i]
n = jsonOut.SizeOfArray("outputs")
for i in range(n):
jsonOut.I = i
png = chilkat2.BinData()
png.AppendEncoded(jsonOut.StringOf("outputs[i].base64"), "base64")
png.WriteFile("symbol" + str(i + 1) + ".png")
print(jsonOut.StringOf("selected[i].text") + ":",
jsonOut.IntOf("outputs[i].width"), "x", jsonOut.IntOf("outputs[i].height"), "px")Formats, have the same methods and the same JSON requests in every supported language: C, C++, C#, VB.NET, Java, Objective-C, Swift, Python, PHP, Perl, Ruby, Node.js, Electron, React Native, Dart / Flutter, Go, Rust, Zig, Delphi, C++Builder, Free Pascal / Lazarus, Classic ASP, VB6, VBScript, FoxPro, DataFlex, PowerBuilder, Xojo, Xbase++, PureBasic, AutoIt, B4A / B4J, LabVIEW, SQL Server and Tcl. See Chilkat Downloads for Every Language.

"mode": "crop" (the default): the upright rectangle of source pixels around the symbol and its quiet zone, 322 × 277 px, copied unchanged.
"mode": "rectify": the same symbol resampled as seen straight on, 315 × 315 px at 7 pixels per module.The request, as JSON
An extract request has the groups of a read request — source, reader, results, parse, limits — plus select, extract and output. Only source is required.
{ "source": { "path": "photo.jpg" }, "extract": { "mode": "rectify" } }The response
The response for the photograph above (the example request also sets the three results.include… options to false, to keep selected[] short):
{
"image": { "width": 640, "height": 480, "format": "jpeg" }, "found": 1, "matched": 1,
"selected": [
{
"symbology": "qr", "frame": 0, "id": 0, "decodeStatus": "decoded", "byteCount": 52,
"text": "https://www.chilkatsoft.com/refdoc/csFormatsRef.html", "textStatus": "valid",
"charset": "utf-8", "charsetSource": "utf8Detected"
}
],
"outputs": [
{
"index": 0, "id": 0, "format": "png", "mimeType": "image/png", "mode": "rectify",
"width": 315, "height": 315, "byteCount": 109213, "quietZoneModules": 4,
"modulePixels": 7, "symbolRect": { "x": 28, "y": 28, "width": 259, "height": 259 },
"sourcePolygon": [
{ "x": 226.11, "y": 74.79 }, { "x": 485.56, "y": 129.01 },
{ "x": 438.85, "y": 350.89 }, { "x": 164.53, "y": 283.49 }
],
"pixelsOutsideSource": 0, "base64": "iVBORw0KGgoAAAANSUhEUgAA..."
}
],
"errors": [], "warnings": []
}| Member | Meaning |
|---|---|
image | The source image, as for read. |
found | The number of symbols the search found. |
matched | The number of those that pass the select filters (before select.occurrence picks one). |
selected[] | The selected symbols, in position order. Each entry is the result entry of read (the results.* options apply) plus decodeStatus. id is the symbol's index among everything the call found, so it is the id a read of the same image reports. |
outputs[] | The images. selected[] and outputs[] are always present and have the same length and order: outputs[i] is the image of selected[i]. |
Finding nothing, or selecting nothing, is success with both arrays empty; found and matched tell the two cases apart. A failed extract returns only errors[]: there is never a partial result, and no file has been written.
select
Choosing which symbols
Without select, every symbol found is extracted. The members of select are filters, and a symbol must pass all that are given.
| Member | Values | Notes |
|---|---|---|
select.text | string | The exact decoded text. A symbol without valid text (textStatus other than valid) does not match. |
select.bytesBase64 | base64 string | The exact payload bytes. "" matches a symbol with an empty payload. |
select.symbology | symbology ID | Only "qr" can be read, so it selects everything in v11.8.0. |
select.occurrence | 1–8192 | Take the n-th match, counting from 1 in position order. A number past the last match is success with nothing selected. |
select.all | bool | true states "every match", which is what happens without occurrence. Together with occurrence it is conflictingOptions. |

{ "source": { "path": "sheet.png" }, "select": { "text": "https://www.chilkatsoft.com" } }{
"image": { "width": 408, "height": 408, "format": "png" }, "found": 4, "matched": 1,
"selected": [
{
"symbology": "qr", "frame": 0, "id": 0, "decodeStatus": "decoded", "byteCount": 27,
"text": "https://www.chilkatsoft.com", "textStatus": "valid", "charset": "utf-8",
"charsetSource": "utf8Detected"
}
],
"outputs": [
{
"index": 0, "id": 0, "format": "png", "mimeType": "image/png", "mode": "crop",
"width": 148, "height": 148, "byteCount": 1011, "quietZoneModules": 4,
"sourceRect": { "x": 28, "y": 20, "width": 148, "height": 148 },
"clippedMargins": { "left": 0, "top": 0, "right": 0, "bottom": 0 },
"base64": "iVBORw0KGgoAAAANSUhEUgAA..."
}
],
"errors": [], "warnings": []
}{ "select": { "occurrence": 3 } } on the same sheet selects the third symbol in position order: found: 4, matched: 4, and one entry with id: 2 (INVERTED: light on dark). A filter that matches nothing gives found: 4, matched: 0 and empty arrays, and the method returns true.
extract
Crop or rectify
The extract group says what the image of a symbol is.
| Member | Values | Default | Notes |
|---|---|---|---|
extract.mode | "crop" · "rectify" | "crop" | A rectangle of the source, or the symbol resampled as seen straight on. |
extract.includeQuietZone | bool | true | Include the four-module quiet zone around the symbol. outputs[i].quietZoneModules reports 4 or 0. |
extract.marginPixels | 0–4096 | 0 | More on every side: source pixels for a crop, output pixels for a rectified image. |
extract.includeUndecoded | bool | false | Also return symbols that are located but cannot be decoded. See below. |
Crop
The extent of a crop is the outline of the symbol (geometry.polygon) widened by the quiet zone. The quiet zone is found by continuing the symbol's own module grid four modules outward, so it follows rotation and perspective. The bounding box of that extent is rounded outward to whole pixels, marginPixels are added on every side, and whatever lies outside the image is cut off.
{
"index": 0, "id": 0, "format": "png", "mimeType": "image/png", "mode": "crop",
"width": 322, "height": 277, "byteCount": 117696, "quietZoneModules": 4,
"sourceRect": { "x": 164, "y": 74, "width": 322, "height": 277 },
"clippedMargins": { "left": 0, "top": 0, "right": 0, "bottom": 0 },
"base64": "iVBORw0KGgoAAAANSUhEUgAA..."
}| Member | Meaning |
|---|---|
sourceRect | { x, y, width, height }: the rectangle of the source that was copied. The PNG has exactly this size. |
clippedMargins | { left, top, right, bottom }: how many pixels of the wanted rectangle lie outside the image on each side. Nothing is invented: a clipped crop is simply smaller. |
- The pixels are copied unchanged, in the format the source decodes to: gray, RGB or RGBA. Alpha is kept (
source.alphaBackgroundis used for the search only). - A JPEG whose Exif orientation was applied is cropped as it is shown.
- The PNG carries the resolution of the source (a pHYs chunk) when the source states one.
- A rotated symbol is not turned: a crop is the upright rectangle around it.
With "marginPixels": 200 the rectangle wanted for the photograph above reaches past all four edges of the 640 × 480 image. The crop is then the whole image, and the response says how much is missing: "sourceRect": { "x": 0, "y": 0, "width": 640, "height": 480 }, "clippedMargins": { "left": 36, "top": 126, "right": 46, "bottom": 71 }.
Rectify
A rectified image shows the symbol as seen straight on: square, with the symbol's own top-left corner at the top left. A rotated or tilted symbol comes out upright, and a mirrored one unmirrored. It is an image of the original pixels, not a regenerated symbol: blur, noise, colors and a light-on-dark symbol stay as they are.
{
"index": 0, "id": 0, "format": "png", "mimeType": "image/png", "mode": "rectify",
"width": 315, "height": 315, "byteCount": 109213, "quietZoneModules": 4,
"modulePixels": 7, "symbolRect": { "x": 28, "y": 28, "width": 259, "height": 259 },
"sourcePolygon": [
{ "x": 226.11, "y": 74.79 }, { "x": 485.56, "y": 129.01 }, { "x": 438.85, "y": 350.89 },
{ "x": 164.53, "y": 283.49 }
],
"pixelsOutsideSource": 0, "base64": "iVBORw0KGgoAAAANSUhEUgAA..."
}| Member | Meaning |
|---|---|
modulePixels | Output pixels per module: the longest side of the symbol on the source, divided by its number of modules and rounded up, so that no detail is lost. |
width, height | (modules + 2 × quietZoneModules) × modulePixels + 2 × marginPixels on both axes. Here (37 + 8) × 7 = 315. |
symbolRect | Where the symbol, without quiet zone, lies in the output. |
sourcePolygon | The points of the source that became the top-left, top-right, bottom-right and bottom-left corners of the output. These four correspondences define the projective mapping that was used. |
pixelsOutsideSource | The number of output pixels whose source point lies outside the image. They are fully transparent, and the PNG then has an alpha channel; otherwise the PNG has the format of the source. |
Each output pixel is the bilinear interpolation of the four source pixels around its source point, computed in integers, so every platform produces the same bytes; an upright symbol with a whole number of pixels per module is copied exactly. Without the quiet zone ("includeQuietZone": false) the image above is 259 × 259 px and symbolRect is the whole image. With "marginPixels": 150 it is 615 × 615 px, and 9,883 of its pixels fall outside the photograph and are transparent.

rotation: 270, mirrored: true): the pixels as they are.
output
Base64 or files
Images are PNG. By default each is returned as base64 in outputs[i].base64; they can also, or instead, be written to files.
| Member | Values | Default | Notes |
|---|---|---|---|
output.format | "png" | "png" | "svg" is unsupportedFeature: an extracted image is made of pixels. |
output.return | "base64" · "none" | "base64" | none requires a destination. |
output.path | string | — | Write the image to this file. For one symbol only: when more than one is selected, the call fails with conflictingOptions at /output/path and nothing is written. Combine it with select.occurrence. |
output.pathTemplate | string containing {index} | — | Write every image, replacing {index} with the one-based position in outputs[]. |
output.overwrite | bool | false | When false, an existing destination fails the call with outputFailed, and nothing is written. |
{ "source": { "path": "sheet.png" },
"extract": { "mode": "rectify" },
"output": { "return": "none", "pathTemplate": "symbol-{index}.png" } }[
{
"index": 0, "id": 0, "width": 148, "height": 148, "byteCount": 1011,
"path": "symbol-1.png"
},
{
"index": 1, "id": 1, "width": 164, "height": 164, "byteCount": 1215,
"path": "symbol-2.png"
},
{
"index": 2, "id": 2, "width": 132, "height": 132, "byteCount": 819,
"path": "symbol-3.png"
},
{
"index": 3, "id": 3, "width": 132, "height": 132, "byteCount": 801,
"path": "symbol-4.png"
}
]Every image is made and held in memory before the first is delivered. A failure up to that point — a timeout, a limit, an existing destination, output.path with several symbols — writes no file at all. Only a write that fails part-way (outputFailed) can leave earlier files behind.
Undecoded symbols
An image of what could not be read
With "includeUndecoded": true the search of detect runs after the search of read, and every located symbol that no decoded symbol covers is added. This gives you the image of a symbol that is too damaged to read: to show it to a person, or to keep it as evidence.

![Its rectified image, returned as outputs[1].](/images/barcode/extract_undecoded.png)
outputs[1].{ "source": { "path": "damaged.png" }, "extract": { "mode": "rectify", "includeUndecoded": true } }{
"symbology": "qr", "frame": 0, "id": 1, "decodeStatus": "failed",
"geometry": {
"bounds": { "x": 205, "y": 30, "width": 125, "height": 125 },
"polygon": [
{ "x": 205, "y": 30 }, { "x": 330, "y": 30 }, { "x": 330, "y": 155 },
{ "x": 205, "y": 155 }
],
"rotation": 0, "moduleSize": 5, "mirrored": false, "inverted": false
},
"evidence": {
"finderPatterns": 3, "functionPatternMatch": 0.93, "timingPatternMatch": 1,
"alignmentPattern": false, "formatInformation": "valid", "formatBitErrors": 0,
"estimatedVersion": 2
}
}- The entry is the candidate entry of
detect— geometry and evidence, no content — with"decodeStatus": "failed". Decoded symbols have"decodeStatus": "decoded". - An undecoded symbol matches
select.symbologyand counts forselect.occurrence, and never matchesselect.textorselect.bytesBase64. - The second search costs about as much as the first.
- Undecoded symbols are added only when the search for decodable ones ran to its end, not after a stop at
reader.maxResults. - A symbol that was decoded and then dropped by
"allowDamaged": falseis not reported as undecoded.
results.includeCrops
Crops attached to a read
When all you want is a picture of each symbol next to its content, there is no need for a second call: "results": { "includeCrops": true } in a read request attaches a crop to every result. It is the image extract makes by default: the upright rectangle around the symbol and its quiet zone, with no margin.
{
"symbology": "qr", "frame": 0, "id": 0, "byteCount": 27,
"text": "https://www.chilkatsoft.com", "textStatus": "valid", "charset": "utf-8",
"charsetSource": "utf8Detected",
"crop": {
"format": "png", "width": 148, "height": 148,
"bytesBase64": "iVBORw0KGgoAAAANSUhEUgAA...", "quietZoneModules": 4,
"sourceRect": { "x": 28, "y": 20, "width": 148, "height": 148 },
"clippedMargins": { "left": 0, "top": 0, "right": 0, "bottom": 0 }
}
}crop.bytesBase64 is the PNG file. The other members are those of a crop of extract. In an extract request results.includeCrops is optionNotApplicable, since the images are in outputs[], and so is reader.assembleStructuredAppend: extract returns single symbols.
Errors
What can go wrong
The failures of reading apply to extract as well. These are its own; the messages are the real ones.
| Code | Path | Message | When |
|---|---|---|---|
conflictingOptions | /output/path | output.path admits a single output and 4 symbols were selected; use output.pathTemplate with {index}, or select one symbol with select.occurrence | output.path was given and more than one symbol was selected. |
outputFailed | /output/pathTemplate | the destination file already exists and output.overwrite is false (output 0) | A destination exists and output.overwrite is false. Nothing is written. |
unsupportedFeature | /output/format | extract returns PNG images only | "format": "svg". |
outOfRange | /extract/marginPixels | — | A rectified image whose margin reaches past the horizon of the symbol's plane: a strongly tilted symbol with a large margin. |
resourceLimit | /extract | — | A rectified image that would exceed limits.maxPixels or 32,768 pixels on a side. |
"stopReason": "maxResults" in a successful response means the search stopped at reader.maxResults or expectedCount; the selection is then among what was found. A timeout or a cancelled call returns false with errors[] and stopReason only.