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;
45 @synthesize operationQueue;
50 if (self = [super init]) {
51 NSOperationQueue *opQueue = [[NSOperationQueue alloc] init];
52 self.operationQueue = opQueue;
57 - (void)willDecodeImage {
58 if ([self.delegate respondsToSelector:@selector(decoder:willDecodeImage:usingSubset:)]) {
59 [self.delegate decoder:self willDecodeImage:self.image usingSubset:self.subsetImage];
63 - (void)progressDecodingImage:(NSString *)progress {
64 if ([self.delegate respondsToSelector:@selector(decoder:decodingImage:usingSubset:progress:)]) {
65 [self.delegate decoder:self decodingImage:self.image usingSubset:self.subsetImage progress:progress];
69 - (void)didDecodeImage:(TwoDDecoderResult *)result {
71 if ([self.delegate respondsToSelector:@selector(decoder:didDecodeImage:usingSubset:withResult:)]) {
72 [self.delegate decoder:self didDecodeImage:self.image usingSubset:self.subsetImage withResult:result];
78 - (void)failedToDecodeImage:(NSString *)reason {
80 if ([self.delegate respondsToSelector:@selector(decoder:failedToDecodeImage:usingSubset:reason:)]) {
81 [self.delegate decoder:self failedToDecodeImage:self.image usingSubset:self.subsetImage reason:reason];
85 #define SUBSET_SIZE 320.0
86 - (void) prepareSubset {
87 CGSize size = [image size];
89 NSLog(@"decoding: image is (%.1f x %.1f), cropRect is (%.1f,%.1f)x(%.1f,%.1f)", size.width, size.height,
90 cropRect.origin.x, cropRect.origin.y, cropRect.size.width, cropRect.size.height);
92 float scale = fminf(1.0f, fmaxf(SUBSET_SIZE / cropRect.size.width, SUBSET_SIZE / cropRect.size.height));
93 CGPoint offset = CGPointMake(-cropRect.origin.x, -cropRect.origin.y);
95 NSLog(@" offset = (%.1f, %.1f), scale = %.3f", offset.x, offset.y, scale);
98 subsetWidth = cropRect.size.width * scale;
99 subsetHeight = cropRect.size.height * scale;
101 subsetBytesPerRow = ((subsetWidth + 0xf) >> 4) << 4;
103 NSLog(@"decoding: image to decode is (%d x %d) (%d bytes/row)", subsetWidth, subsetHeight, subsetBytesPerRow);
106 subsetData = (unsigned char *)malloc(subsetBytesPerRow * subsetHeight);
108 NSLog(@"allocated %d bytes of memory", subsetBytesPerRow * subsetHeight);
111 CGColorSpaceRef grayColorSpace = CGColorSpaceCreateDeviceGray();
114 CGBitmapContextCreate(subsetData, subsetWidth, subsetHeight,
115 8, subsetBytesPerRow, grayColorSpace,
117 CGColorSpaceRelease(grayColorSpace);
118 CGContextSetInterpolationQuality(ctx, kCGInterpolationNone);
119 CGContextSetAllowsAntialiasing(ctx, false);
120 // adjust the coordinate system
121 CGContextTranslateCTM(ctx, 0.0, subsetHeight);
122 CGContextScaleCTM(ctx, 1.0, -1.0);
125 NSLog(@"created %dx%d bitmap context", subsetWidth, subsetHeight);
128 UIGraphicsPushContext(ctx);
129 CGRect rect = CGRectMake(offset.x * scale, offset.y * scale, scale * size.width, scale * size.height);
131 NSLog(@"rect for image = (%.1f,%.1f)x(%.1f,%.1f)", rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
133 [image drawInRect:rect];
134 UIGraphicsPopContext();
137 NSLog(@"drew image into %d(%d)x%d bitmap context", subsetWidth, subsetBytesPerRow, subsetHeight);
141 NSLog(@"flushed context");
144 CGImageRef subsetImageRef = CGBitmapContextCreateImage(ctx);
146 NSLog(@"created CGImage from context");
149 self.subsetImage = [UIImage imageWithCGImage:subsetImageRef];
150 CGImageRelease(subsetImageRef);
152 CGContextRelease(ctx);
154 NSLog(@"released context");
158 - (void)decode:(id)arg {
159 NSAutoreleasePool* mainpool = [[NSAutoreleasePool alloc] init];
161 //NSSet *formatReaders = [FormatReader formatReaders];
162 NSSet *formatReaders = self.readers;
163 Ref<LuminanceSource> source (new GrayBytesMonochromeBitmapSource(subsetData, subsetWidth, subsetHeight, subsetBytesPerRow));
164 Ref<Binarizer> binarizer (new GlobalHistogramBinarizer(source));
165 Ref<BinaryBitmap> grayImage (new BinaryBitmap(binarizer));
167 NSLog(@"created GrayBytesMonochromeBitmapSource", subsetWidth, subsetHeight);
168 NSLog(@"grayImage count = %d", grayImage->count());
171 TwoDDecoderResult *decoderResult = nil;
174 for (int i = 0; !decoderResult && i < 4; i++) {
176 for (FormatReader *reader in formatReaders) {
177 NSAutoreleasePool *secondarypool = [[NSAutoreleasePool alloc] init];
180 NSLog(@"decoding gray image");
182 Ref<Result> result([reader decode:grayImage]);
184 NSLog(@"gray image decoded");
187 Ref<String> resultText(result->getText());
188 const char *cString = resultText->getText().c_str();
189 const std::vector<Ref<ResultPoint> > &resultPoints = result->getResultPoints();
190 NSMutableArray *points =
191 [[NSMutableArray alloc ] initWithCapacity:resultPoints.size()];
193 for (size_t i = 0; i < resultPoints.size(); i++) {
194 const Ref<ResultPoint> &rp = resultPoints[i];
195 CGPoint p = CGPointMake(rp->getX(), rp->getY());
196 [points addObject:[NSValue valueWithCGPoint:p]];
199 NSString *resultString = [NSString stringWithCString:cString
200 encoding:NSUTF8StringEncoding];
202 decoderResult = [[TwoDDecoderResult resultWithText:resultString
203 points:points] retain];
205 } catch (ReaderException &rex) {
206 NSLog(@"failed to decode, caught ReaderException '%s'",
208 } catch (IllegalArgumentException &iex) {
209 NSLog(@"failed to decode, caught IllegalArgumentException '%s'",
212 NSLog(@"Caught unknown exception!");
214 [secondarypool release];
218 if (!decoderResult) {
220 NSLog(@"rotating gray image");
222 grayImage = grayImage->rotateCounterClockwise();
224 NSLog(@"gray image rotated");
231 self.subsetData = NULL;
234 [self performSelectorOnMainThread:@selector(didDecodeImage:)
235 withObject:decoderResult
238 [self performSelectorOnMainThread:@selector(failedToDecodeImage:)
239 withObject:NSLocalizedString(@"Decoder BarcodeDetectionFailure", @"No barcode detected.")
246 NSLog(@"finished decoding.");
251 - (void) decodeImage:(UIImage *)i {
252 [self decodeImage:i cropRect:CGRectMake(0.0f, 0.0f, i.size.width, i.size.height)];
256 - (void) asyncDecodeImage {
257 [self prepareSubset];
258 [self willDecodeImage];
259 [self performSelectorOnMainThread:@selector(willDecodeImage)
262 [self performSelectorOnMainThread:@selector(progressDecodingImage:)
263 withObject:NSLocalizedString(@"Decoder MessageWhileDecoding", @"Decoding ...")
265 /* NSInvocationOperation *op = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(decode:) object:nil];
266 [operationQueue addOperation:op];
270 - (void) decodeImage:(UIImage *)i cropRect:(CGRect)cr {
273 NSInvocationOperation *op = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(asyncDecodeImage) object:nil];
274 [operationQueue addOperation:op];
281 [subsetImage release];
282 if (subsetData) free(subsetData);
283 [operationQueue release];