5 // Created by Christian Brunschen on 31/03/2008.
8 * Copyright 2008 ZXing authors
10 * Licensed under the Apache License, Version 2.0 (the "License");
11 * you may not use this file except in compliance with the License.
12 * You may obtain a copy of the License at
14 * http://www.apache.org/licenses/LICENSE-2.0
16 * Unless required by applicable law or agreed to in writing, software
17 * distributed under the License is distributed on an "AS IS" BASIS,
18 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19 * See the License for the specific language governing permissions and
20 * limitations under the License.
24 #import "TwoDDecoderResult.h"
25 #import "FormatReader.h"
27 #include <zxing/BinaryBitmap.h>
28 #include <zxing/ReaderException.h>
29 #include <zxing/common/IllegalArgumentException.h>
30 #include <zxing/common/GlobalHistogramBinarizer.h>
31 #include "GrayBytesMonochromeBitmapSource.h"
33 using namespace zxing;
35 @implementation Decoder
39 @synthesize subsetImage;
40 @synthesize subsetData;
41 @synthesize subsetWidth;
42 @synthesize subsetHeight;
43 @synthesize subsetBytesPerRow;
46 - (void)willDecodeImage {
47 if ([self.delegate respondsToSelector:@selector(decoder:willDecodeImage:usingSubset:)]) {
48 [self.delegate decoder:self willDecodeImage:self.image usingSubset:self.subsetImage];
52 - (void)progressDecodingImage:(NSString *)progress {
53 if ([self.delegate respondsToSelector:@selector(decoder:decodingImage:usingSubset:progress:)]) {
54 [self.delegate decoder:self decodingImage:self.image usingSubset:self.subsetImage progress:progress];
58 - (void)didDecodeImage:(TwoDDecoderResult *)result {
59 if ([self.delegate respondsToSelector:@selector(decoder:didDecodeImage:usingSubset:withResult:)]) {
60 [self.delegate decoder:self didDecodeImage:self.image usingSubset:self.subsetImage withResult:result];
66 - (void)failedToDecodeImage:(NSString *)reason {
67 if ([self.delegate respondsToSelector:@selector(decoder:failedToDecodeImage:usingSubset:reason:)]) {
68 [self.delegate decoder:self failedToDecodeImage:self.image usingSubset:self.subsetImage reason:reason];
72 #define SUBSET_SIZE 320.0
73 - (void) prepareSubset {
74 CGSize size = [image size];
76 NSLog(@"decoding: image is (%.1f x %.1f), cropRect is (%.1f,%.1f)x(%.1f,%.1f)", size.width, size.height,
77 cropRect.origin.x, cropRect.origin.y, cropRect.size.width, cropRect.size.height);
79 float scale = fminf(1.0f, fmaxf(SUBSET_SIZE / cropRect.size.width, SUBSET_SIZE / cropRect.size.height));
80 CGPoint offset = CGPointMake(-cropRect.origin.x, -cropRect.origin.y);
82 NSLog(@" offset = (%.1f, %.1f), scale = %.3f", offset.x, offset.y, scale);
85 subsetWidth = cropRect.size.width * scale;
86 subsetHeight = cropRect.size.height * scale;
88 subsetBytesPerRow = ((subsetWidth + 0xf) >> 4) << 4;
90 NSLog(@"decoding: image to decode is (%d x %d) (%d bytes/row)", subsetWidth, subsetHeight, subsetBytesPerRow);
93 subsetData = (unsigned char *)malloc(subsetBytesPerRow * subsetHeight);
95 NSLog(@"allocated %d bytes of memory", subsetBytesPerRow * subsetHeight);
98 CGColorSpaceRef grayColorSpace = CGColorSpaceCreateDeviceGray();
101 CGBitmapContextCreate(subsetData, subsetWidth, subsetHeight,
102 8, subsetBytesPerRow, grayColorSpace,
104 CGColorSpaceRelease(grayColorSpace);
105 CGContextSetInterpolationQuality(ctx, kCGInterpolationNone);
106 CGContextSetAllowsAntialiasing(ctx, false);
107 // adjust the coordinate system
108 CGContextTranslateCTM(ctx, 0.0, subsetHeight);
109 CGContextScaleCTM(ctx, 1.0, -1.0);
112 NSLog(@"created %dx%d bitmap context", subsetWidth, subsetHeight);
115 UIGraphicsPushContext(ctx);
116 CGRect rect = CGRectMake(offset.x * scale, offset.y * scale, scale * size.width, scale * size.height);
118 NSLog(@"rect for image = (%.1f,%.1f)x(%.1f,%.1f)", rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
120 [image drawInRect:rect];
121 UIGraphicsPopContext();
124 NSLog(@"drew image into %d(%d)x%d bitmap context", subsetWidth, subsetBytesPerRow, subsetHeight);
128 NSLog(@"flushed context");
131 CGImageRef subsetImageRef = CGBitmapContextCreateImage(ctx);
133 NSLog(@"created CGImage from context");
136 self.subsetImage = [UIImage imageWithCGImage:subsetImageRef];
137 CGImageRelease(subsetImageRef);
139 CGContextRelease(ctx);
141 NSLog(@"released context");
145 - (void)decode:(id)arg {
146 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
149 NSSet *formatReaders = [FormatReader formatReaders];
151 Ref<LuminanceSource> source (new GrayBytesMonochromeBitmapSource(subsetData, subsetWidth, subsetHeight, subsetBytesPerRow));
153 Ref<Binarizer> binarizer (new GlobalHistogramBinarizer(source));
154 Ref<BinaryBitmap> grayImage (new BinaryBitmap(binarizer));
156 NSLog(@"created GrayBytesMonochromeBitmapSource", subsetWidth, subsetHeight);
157 NSLog(@"grayImage count = %d", grayImage->count());
160 TwoDDecoderResult *decoderResult = nil;
163 for (int i = 0; !decoderResult && i < 4; i++) {
165 for (FormatReader *reader in formatReaders) {
168 NSLog(@"decoding gray image");
170 Ref<Result> result([reader decode:grayImage]);
172 NSLog(@"gray image decoded");
175 Ref<String> resultText(result->getText());
176 const char *cString = resultText->getText().c_str();
177 const std::vector<Ref<ResultPoint> > &resultPoints = result->getResultPoints();
178 NSMutableArray *points =
179 [NSMutableArray arrayWithCapacity:resultPoints.size()];
181 for (size_t i = 0; i < resultPoints.size(); i++) {
182 const Ref<ResultPoint> &rp = resultPoints[i];
183 CGPoint p = CGPointMake(rp->getX(), rp->getY());
184 [points addObject:[NSValue valueWithCGPoint:p]];
187 NSString *resultString = [NSString stringWithCString:cString
188 encoding:NSUTF8StringEncoding];
190 decoderResult = [[TwoDDecoderResult resultWithText:resultString
191 points:points] retain];
192 } catch (ReaderException &rex) {
193 NSLog(@"failed to decode, caught ReaderException '%s'",
195 } catch (IllegalArgumentException &iex) {
196 NSLog(@"failed to decode, caught IllegalArgumentException '%s'",
199 NSLog(@"Caught unknown exception!");
204 if (!decoderResult) {
206 NSLog(@"rotating gray image");
208 grayImage = grayImage->rotateCounterClockwise();
210 NSLog(@"gray image rotated");
217 self.subsetData = NULL;
220 [self performSelectorOnMainThread:@selector(didDecodeImage:)
221 withObject:decoderResult
224 [self performSelectorOnMainThread:@selector(failedToDecodeImage:)
225 withObject:NSLocalizedString(@"Decoder BarcodeDetectionFailure", @"No barcode detected.")
231 NSLog(@"finished decoding.");
234 // if this is not the main thread, then we end it
235 if (![NSThread isMainThread]) {
240 - (void) decodeImage:(UIImage *)i {
241 [self decodeImage:i cropRect:CGRectMake(0.0f, 0.0f, i.size.width, i.size.height)];
244 - (void) decodeImage:(UIImage *)i cropRect:(CGRect)cr {
248 [self prepareSubset];
249 [self willDecodeImage];
250 [self performSelectorOnMainThread:@selector(progressDecodingImage:)
251 withObject:NSLocalizedString(@"Decoder MessageWhileDecoding", @"Decoding ...")
254 [NSThread detachNewThreadSelector:@selector(decode:)
261 [subsetImage release];
262 if (subsetData) free(subsetData);