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];
64 - (void)failedToDecodeImage:(NSString *)reason {
65 if ([self.delegate respondsToSelector:@selector(decoder:failedToDecodeImage:usingSubset:reason:)]) {
66 [self.delegate decoder:self failedToDecodeImage:self.image usingSubset:self.subsetImage reason:reason];
70 #define SUBSET_SIZE 320.0
71 - (void) prepareSubset {
72 CGSize size = [image size];
74 NSLog(@"decoding: image is (%.1f x %.1f), cropRect is (%.1f,%.1f)x(%.1f,%.1f)", size.width, size.height,
75 cropRect.origin.x, cropRect.origin.y, cropRect.size.width, cropRect.size.height);
77 float scale = fminf(1.0f, fmaxf(SUBSET_SIZE / cropRect.size.width, SUBSET_SIZE / cropRect.size.height));
78 CGPoint offset = CGPointMake(-cropRect.origin.x, -cropRect.origin.y);
80 NSLog(@" offset = (%.1f, %.1f), scale = %.3f", offset.x, offset.y, scale);
83 subsetWidth = cropRect.size.width * scale;
84 subsetHeight = cropRect.size.height * scale;
86 subsetBytesPerRow = ((subsetWidth + 0xf) >> 4) << 4;
88 NSLog(@"decoding: image to decode is (%d x %d) (%d bytes/row)", subsetWidth, subsetHeight, subsetBytesPerRow);
91 subsetData = (unsigned char *)malloc(subsetBytesPerRow * subsetHeight);
93 NSLog(@"allocated %d bytes of memory", subsetBytesPerRow * subsetHeight);
96 CGColorSpaceRef grayColorSpace = CGColorSpaceCreateDeviceGray();
99 CGBitmapContextCreate(subsetData, subsetWidth, subsetHeight,
100 8, subsetBytesPerRow, grayColorSpace,
102 CGColorSpaceRelease(grayColorSpace);
103 CGContextSetInterpolationQuality(ctx, kCGInterpolationNone);
104 CGContextSetAllowsAntialiasing(ctx, false);
105 // adjust the coordinate system
106 CGContextTranslateCTM(ctx, 0.0, subsetHeight);
107 CGContextScaleCTM(ctx, 1.0, -1.0);
110 NSLog(@"created %dx%d bitmap context", subsetWidth, subsetHeight);
113 UIGraphicsPushContext(ctx);
114 CGRect rect = CGRectMake(offset.x * scale, offset.y * scale, scale * size.width, scale * size.height);
116 NSLog(@"rect for image = (%.1f,%.1f)x(%.1f,%.1f)", rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
118 [image drawInRect:rect];
119 UIGraphicsPopContext();
122 NSLog(@"drew image into %d(%d)x%d bitmap context", subsetWidth, subsetBytesPerRow, subsetHeight);
126 NSLog(@"flushed context");
129 CGImageRef subsetImageRef = CGBitmapContextCreateImage(ctx);
131 NSLog(@"created CGImage from context");
134 self.subsetImage = [UIImage imageWithCGImage:subsetImageRef];
135 CGImageRelease(subsetImageRef);
137 CGContextRelease(ctx);
139 NSLog(@"released context");
143 - (void)decode:(id)arg {
144 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
147 NSSet *formatReaders = [FormatReader formatReaders];
149 Ref<LuminanceSource> source (new GrayBytesMonochromeBitmapSource(subsetData, subsetWidth, subsetHeight, subsetBytesPerRow));
151 Ref<Binarizer> binarizer (new GlobalHistogramBinarizer(source));
152 Ref<BinaryBitmap> grayImage (new BinaryBitmap(binarizer));
154 NSLog(@"created GrayBytesMonochromeBitmapSource", subsetWidth, subsetHeight);
155 NSLog(@"grayImage count = %d", grayImage->count());
158 TwoDDecoderResult *decoderResult = nil;
161 for (int i = 0; !decoderResult && i < 4; i++) {
163 for (FormatReader *reader in formatReaders) {
166 NSLog(@"decoding gray image");
168 Ref<Result> result([reader decode:grayImage]);
170 NSLog(@"gray image decoded");
173 Ref<String> resultText(result->getText());
174 const char *cString = resultText->getText().c_str();
175 const std::vector<Ref<ResultPoint> > &resultPoints = result->getResultPoints();
176 NSMutableArray *points =
177 [NSMutableArray arrayWithCapacity:resultPoints.size()];
179 for (size_t i = 0; i < resultPoints.size(); i++) {
180 const Ref<ResultPoint> &rp = resultPoints[i];
181 CGPoint p = CGPointMake(rp->getX(), rp->getY());
182 [points addObject:[NSValue valueWithCGPoint:p]];
185 NSString *resultString = [NSString stringWithCString:cString
186 encoding:NSUTF8StringEncoding];
188 decoderResult = [TwoDDecoderResult resultWithText:resultString
190 } catch (ReaderException &rex) {
191 NSLog(@"failed to decode, caught ReaderException '%s'",
193 } catch (IllegalArgumentException &iex) {
194 NSLog(@"failed to decode, caught IllegalArgumentException '%s'",
197 NSLog(@"Caught unknown exception!");
202 if (!decoderResult) {
204 NSLog(@"rotating gray image");
206 grayImage = grayImage->rotateCounterClockwise();
208 NSLog(@"gray image rotated");
215 [self performSelectorOnMainThread:@selector(didDecodeImage:)
216 withObject:decoderResult
219 [self performSelectorOnMainThread:@selector(failedToDecodeImage:)
220 withObject:NSLocalizedString(@"Decoder BarcodeDetectionFailure", @"No barcode detected.")
225 self.subsetData = NULL;
229 NSLog(@"finished decoding.");
232 // if this is not the main thread, then we end it
233 if (![NSThread isMainThread]) {
238 - (void) decodeImage:(UIImage *)i {
239 [self decodeImage:i cropRect:CGRectMake(0.0f, 0.0f, image.size.width, image.size.height)];
242 - (void) decodeImage:(UIImage *)i cropRect:(CGRect)cr {
246 [self prepareSubset];
247 [self willDecodeImage];
248 [self performSelectorOnMainThread:@selector(progressDecodingImage:)
249 withObject:NSLocalizedString(@"Decoder MessageWhileDecoding", @"Decoding ...")
252 [NSThread detachNewThreadSelector:@selector(decode:)
259 [subsetImage release];
260 if (subsetData) free(subsetData);