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 <zxing/common/GreyscaleLuminanceSource.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
164 (new GreyscaleLuminanceSource(subsetData, subsetBytesPerRow, subsetHeight, 0, 0, subsetWidth, subsetHeight));
165 Ref<Binarizer> binarizer (new GlobalHistogramBinarizer(source));
166 Ref<BinaryBitmap> grayImage (new BinaryBitmap(binarizer));
168 NSLog(@"created GreyscaleLuminanceSource", subsetWidth, subsetHeight);
169 NSLog(@"grayImage count = %d", grayImage->count());
172 TwoDDecoderResult *decoderResult = nil;
175 for (int i = 0; !decoderResult && i < 4; i++) {
177 for (FormatReader *reader in formatReaders) {
178 NSAutoreleasePool *secondarypool = [[NSAutoreleasePool alloc] init];
181 NSLog(@"decoding gray image");
183 Ref<Result> result([reader decode:grayImage]);
185 NSLog(@"gray image decoded");
188 Ref<String> resultText(result->getText());
189 const char *cString = resultText->getText().c_str();
190 const std::vector<Ref<ResultPoint> > &resultPoints = result->getResultPoints();
191 NSMutableArray *points =
192 [[NSMutableArray alloc ] initWithCapacity:resultPoints.size()];
194 for (size_t i = 0; i < resultPoints.size(); i++) {
195 const Ref<ResultPoint> &rp = resultPoints[i];
196 CGPoint p = CGPointMake(rp->getX(), rp->getY());
197 [points addObject:[NSValue valueWithCGPoint:p]];
200 NSString *resultString = [NSString stringWithCString:cString
201 encoding:NSUTF8StringEncoding];
203 decoderResult = [[TwoDDecoderResult resultWithText:resultString
204 points:points] retain];
206 } catch (ReaderException &rex) {
207 NSLog(@"failed to decode, caught ReaderException '%s'",
209 } catch (IllegalArgumentException &iex) {
210 NSLog(@"failed to decode, caught IllegalArgumentException '%s'",
213 NSLog(@"Caught unknown exception!");
215 [secondarypool release];
219 if (!decoderResult) {
221 NSLog(@"rotating gray image");
223 grayImage = grayImage->rotateCounterClockwise();
225 NSLog(@"gray image rotated");
232 self.subsetData = NULL;
235 [self performSelectorOnMainThread:@selector(didDecodeImage:)
236 withObject:decoderResult
239 [self performSelectorOnMainThread:@selector(failedToDecodeImage:)
240 withObject:NSLocalizedString(@"Decoder BarcodeDetectionFailure", @"No barcode detected.")
247 NSLog(@"finished decoding.");
252 - (void) decodeImage:(UIImage *)i {
253 [self decodeImage:i cropRect:CGRectMake(0.0f, 0.0f, i.size.width, i.size.height)];
257 - (void) asyncDecodeImage {
258 [self prepareSubset];
259 [self willDecodeImage];
260 [self performSelectorOnMainThread:@selector(willDecodeImage)
263 [self performSelectorOnMainThread:@selector(progressDecodingImage:)
264 withObject:NSLocalizedString(@"Decoder MessageWhileDecoding", @"Decoding ...")
266 /* NSInvocationOperation *op = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(decode:) object:nil];
267 [operationQueue addOperation:op];
271 - (void) decodeImage:(UIImage *)i cropRect:(CGRect)cr {
274 NSInvocationOperation *op = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(asyncDecodeImage) object:nil];
275 [operationQueue addOperation:op];
282 [subsetImage release];
283 if (subsetData) free(subsetData);
284 [operationQueue release];