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 // for debug purposes.
136 // UIImageWriteToSavedPhotosAlbum(self.subsetImage, nil, nil, nil);
138 CGImageRelease(subsetImageRef);
140 CGContextRelease(ctx);
142 NSLog(@"released context");
146 - (void)decode:(id)arg {
147 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
150 NSSet *formatReaders = [FormatReader formatReaders];
152 Ref<LuminanceSource> source (new GrayBytesMonochromeBitmapSource(subsetData, subsetWidth, subsetHeight, subsetBytesPerRow));
154 Ref<Binarizer> binarizer (new GlobalHistogramBinarizer(source));
155 Ref<BinaryBitmap> grayImage (new BinaryBitmap(binarizer));
157 NSLog(@"created GrayBytesMonochromeBitmapSource", subsetWidth, subsetHeight);
158 NSLog(@"grayImage count = %d", grayImage->count());
161 TwoDDecoderResult *decoderResult = nil;
164 for (int i = 0; !decoderResult && i < 4; i++) {
166 for (FormatReader *reader in formatReaders) {
169 NSLog(@"decoding gray image");
171 Ref<Result> result([reader decode:grayImage]);
173 NSLog(@"gray image decoded");
176 Ref<String> resultText(result->getText());
177 const char *cString = resultText->getText().c_str();
178 const std::vector<Ref<ResultPoint> > &resultPoints = result->getResultPoints();
179 NSMutableArray *points =
180 [NSMutableArray arrayWithCapacity:resultPoints.size()];
182 for (size_t i = 0; i < resultPoints.size(); i++) {
183 const Ref<ResultPoint> &rp = resultPoints[i];
184 CGPoint p = CGPointMake(rp->getX(), rp->getY());
185 [points addObject:[NSValue valueWithCGPoint:p]];
188 NSString *resultString = [NSString stringWithCString:cString
189 encoding:NSUTF8StringEncoding];
191 decoderResult = [TwoDDecoderResult resultWithText:resultString
193 } catch (ReaderException &rex) {
194 NSLog(@"failed to decode, caught ReaderException '%s'",
196 } catch (IllegalArgumentException &iex) {
197 NSLog(@"failed to decode, caught IllegalArgumentException '%s'",
200 NSLog(@"Caught unknown exception!");
205 if (!decoderResult) {
207 NSLog(@"rotating gray image");
209 grayImage = grayImage->rotateCounterClockwise();
211 NSLog(@"gray image rotated");
218 [self performSelectorOnMainThread:@selector(didDecodeImage:)
219 withObject:decoderResult
222 [self performSelectorOnMainThread:@selector(failedToDecodeImage:)
223 withObject:NSLocalizedString(@"Decoder BarcodeDetectionFailure", @"No barcode detected.")
228 self.subsetData = NULL;
232 NSLog(@"finished decoding.");
235 // if this is not the main thread, then we end it
236 if (![NSThread isMainThread]) {
241 - (void) decodeImage:(UIImage *)i {
242 [self decodeImage:i cropRect:CGRectMake(0.0f, 0.0f, image.size.width, image.size.height)];
245 - (void) decodeImage:(UIImage *)i cropRect:(CGRect)cr {
249 [self prepareSubset];
250 [self willDecodeImage];
251 [self performSelectorOnMainThread:@selector(progressDecodingImage:)
252 withObject:NSLocalizedString(@"Decoder MessageWhileDecoding", @"Decoding ...")
255 [NSThread detachNewThreadSelector:@selector(decode:)
262 [subsetImage release];
263 if (subsetData) free(subsetData);