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"
26 #include <zxing/qrcode/QRCodeReader.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;
34 using namespace zxing::qrcode;
36 @implementation Decoder
40 @synthesize subsetImage;
41 @synthesize subsetData;
42 @synthesize subsetWidth;
43 @synthesize subsetHeight;
44 @synthesize subsetBytesPerRow;
47 - (void)willDecodeImage {
48 [self.delegate decoder:self willDecodeImage:self.image usingSubset:self.subsetImage];
51 - (void)progressDecodingImage:(NSString *)progress {
52 [self.delegate decoder:self
53 decodingImage:self.image
54 usingSubset:self.subsetImage
58 - (void)didDecodeImage:(TwoDDecoderResult *)result {
59 [self.delegate decoder:self didDecodeImage:self.image usingSubset:self.subsetImage withResult:result];
62 - (void)failedToDecodeImage:(NSString *)reason {
63 [self.delegate decoder:self failedToDecodeImage:self.image usingSubset:self.subsetImage reason:reason];
66 #define SUBSET_SIZE 320.0
67 - (void) prepareSubset {
68 CGSize size = [image size];
70 NSLog(@"decoding: image is (%.1f x %.1f), cropRect is (%.1f,%.1f)x(%.1f,%.1f)", size.width, size.height,
71 cropRect.origin.x, cropRect.origin.y, cropRect.size.width, cropRect.size.height);
73 float scale = fminf(1.0f, fmaxf(SUBSET_SIZE / cropRect.size.width, SUBSET_SIZE / cropRect.size.height));
74 CGPoint offset = CGPointMake(-cropRect.origin.x, -cropRect.origin.y);
76 NSLog(@" offset = (%.1f, %.1f), scale = %.3f", offset.x, offset.y, scale);
79 subsetWidth = cropRect.size.width * scale;
80 subsetHeight = cropRect.size.height * scale;
82 subsetBytesPerRow = ((subsetWidth + 0xf) >> 4) << 4;
84 NSLog(@"decoding: image to decode is (%d x %d) (%d bytes/row)", subsetWidth, subsetHeight, subsetBytesPerRow);
87 subsetData = (unsigned char *)malloc(subsetBytesPerRow * subsetHeight);
89 NSLog(@"allocated %d bytes of memory", subsetBytesPerRow * subsetHeight);
92 CGColorSpaceRef grayColorSpace = CGColorSpaceCreateDeviceGray();
95 CGBitmapContextCreate(subsetData, subsetWidth, subsetHeight,
96 8, subsetBytesPerRow, grayColorSpace,
98 CGColorSpaceRelease(grayColorSpace);
99 CGContextSetInterpolationQuality(ctx, kCGInterpolationNone);
100 CGContextSetAllowsAntialiasing(ctx, false);
101 // adjust the coordinate system
102 CGContextTranslateCTM(ctx, 0.0, subsetHeight);
103 CGContextScaleCTM(ctx, 1.0, -1.0);
106 NSLog(@"created %dx%d bitmap context", subsetWidth, subsetHeight);
109 UIGraphicsPushContext(ctx);
110 CGRect rect = CGRectMake(offset.x * scale, offset.y * scale, scale * size.width, scale * size.height);
112 NSLog(@"rect for image = (%.1f,%.1f)x(%.1f,%.1f)", rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
114 [image drawInRect:rect];
115 UIGraphicsPopContext();
118 NSLog(@"drew image into %d(%d)x%d bitmap context", subsetWidth, subsetBytesPerRow, subsetHeight);
122 NSLog(@"flushed context");
125 CGImageRef subsetImageRef = CGBitmapContextCreateImage(ctx);
127 NSLog(@"created CGImage from context");
130 self.subsetImage = [UIImage imageWithCGImage:subsetImageRef];
131 CGImageRelease(subsetImageRef);
133 CGContextRelease(ctx);
135 NSLog(@"released context");
139 - (void)decode:(id)arg {
140 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
144 NSLog(@"created QRCoreReader");
147 Ref<LuminanceSource> source (new GrayBytesMonochromeBitmapSource(subsetData, subsetWidth, subsetHeight, subsetBytesPerRow));
149 Ref<Binarizer> binarizer (new GlobalHistogramBinarizer(source));
150 Ref<BinaryBitmap> grayImage (new BinaryBitmap(binarizer));
152 NSLog(@"created GrayBytesMonochromeBitmapSource", subsetWidth, subsetHeight);
153 NSLog(@"grayImage count = %d", grayImage->count());
156 TwoDDecoderResult *decoderResult = nil;
159 for (int i = 0; !decoderResult && i < 4; i++) {
164 NSLog(@"decoding gray image");
166 Ref<Result> result(reader.decode(grayImage));
168 NSLog(@"gray image decoded");
171 Ref<String> resultText(result->getText());
172 const char *cString = resultText->getText().c_str();
173 std::vector<Ref<ResultPoint> > resultPoints = result->getResultPoints();
174 NSMutableArray *points =
175 [NSMutableArray arrayWithCapacity:resultPoints.size()];
177 for (size_t i = 0; i < resultPoints.size(); i++) {
178 Ref<ResultPoint> rp(resultPoints[i]);
179 CGPoint p = CGPointMake(rp->getX(), rp->getY());
180 [points addObject:[NSValue valueWithCGPoint:p]];
183 NSString *resultString = [NSString stringWithCString:cString
184 encoding:NSUTF8StringEncoding];
186 decoderResult = [TwoDDecoderResult resultWithText:resultString
188 } catch (ReaderException rex) {
189 NSLog(@"failed to decode, caught ReaderException '%s'",
191 } catch (IllegalArgumentException iex) {
192 NSLog(@"failed to decode, caught IllegalArgumentException '%s'",
195 NSLog(@"Caught unknown exception!");
199 if (!decoderResult) {
201 NSLog(@"rotating gray image");
203 grayImage = grayImage->rotateCounterClockwise();
205 NSLog(@"gray image rotated");
212 [self performSelectorOnMainThread:@selector(didDecodeImage:)
213 withObject:decoderResult
216 [self performSelectorOnMainThread:@selector(failedToDecodeImage:)
217 withObject:NSLocalizedString(@"Decoder BarcodeDetectionFailure", @"No barcode detected.")
222 self.subsetData = NULL;
226 NSLog(@"finished decoding.");
229 // if this is not the main thread, then we end it
230 if (![NSThread isMainThread]) {
235 - (void) decodeImage:(UIImage *)i {
236 [self decodeImage:i cropRect:CGRectMake(0.0f, 0.0f, image.size.width, image.size.height)];
239 - (void) decodeImage:(UIImage *)i cropRect:(CGRect)cr {
243 [self prepareSubset];
244 [self.delegate decoder:self willDecodeImage:i usingSubset:self.subsetImage];
247 [self performSelectorOnMainThread:@selector(progressDecodingImage:)
248 withObject:NSLocalizedString(@"Decoder MessageWhileDecoding", @"Decoding ...")
251 [NSThread detachNewThreadSelector:@selector(decode:)
258 [subsetImage release];
259 if (subsetData) free(subsetData);