GithubHelp home page GithubHelp logo

zxingify-objc's Introduction

zxingify-objc

ZXingObjC is a full Objective-C port of ZXing ("Zebra Crossing"), a Java barcode image processing library. It is designed to be used on both iOS devices and in Mac applications.

The following barcodes are currently supported for both encoding and decoding:

  • UPC-A and UPC-E
  • EAN-8 and EAN-13
  • Code 39
  • Code 93
  • Code 128
  • ITF
  • Codabar
  • RSS-14 (all variants)
  • QR Code
  • Data Matrix
  • Maxicode
  • Aztec ('beta' quality)
  • PDF 417 ('beta' quality)

ZXingObjC currently has feature parity with ZXing version 3.3.3.

Requirements

ZXingObjC requires Xcode 13.0 and above, targeting either iOS 11.0 and above, or Mac OS X 10.15 Catalina and above.

Usage

Encoding:

NSError *error = nil;
ZXMultiFormatWriter *writer = [ZXMultiFormatWriter writer];
ZXBitMatrix* result = [writer encode:@"A string to encode"
                              format:kBarcodeFormatQRCode
                               width:500
                              height:500
                               error:&error];
if (result) {
  CGImageRef image = CGImageRetain([[ZXImage imageWithMatrix:result] cgimage]);

  // This CGImageRef image can be placed in a UIImage, NSImage, or written to a file.
  
  CGImageRelease(image);
} else {
  NSString *errorMessage = [error localizedDescription];
}

Decoding:

CGImageRef imageToDecode;  // Given a CGImage in which we are looking for barcodes

ZXLuminanceSource *source = [[[ZXCGImageLuminanceSource alloc] initWithCGImage:imageToDecode] autorelease];
ZXBinaryBitmap *bitmap = [ZXBinaryBitmap binaryBitmapWithBinarizer:[ZXHybridBinarizer binarizerWithSource:source]];

NSError *error = nil;

// There are a number of hints we can give to the reader, including
// possible formats, allowed lengths, and the string encoding.
ZXDecodeHints *hints = [ZXDecodeHints hints];

ZXMultiFormatReader *reader = [ZXMultiFormatReader reader];
ZXResult *result = [reader decode:bitmap
                            hints:hints
                            error:&error];
if (result) {
  // The coded result as a string. The raw data can be accessed with
  // result.rawBytes and result.length.
  NSString *contents = result.text;

  // The barcode format, such as a QR code or UPC-A
  ZXBarcodeFormat format = result.barcodeFormat;
} else {
  // Use error to determine why we didn't get a result, such as a barcode
  // not being found, an invalid checksum, or a format inconsistency.
}

Installation

We highly recommend Carthage as module manager.

Carthage

ZXingObjC can be installed using Carthage. After installing Carthage just add ZXingObjC to your Cartfile:

github "zxingify/zxingify-objc" ~> 3.6.9

CocoaPods

CocoaPods is a dependency manager for Swift and Objective-C Cocoa projects. After installing CocoaPods add ZXingObjC to your Podfile:

platform :ios, '11.0'
pod 'ZXingObjC', '~> 3.6.9'

Examples

ZXingObjC includes several example applications found in "examples" folder:

  • BarcodeScanner - An iOS application that captures video from the camera, scans for barcodes and displays results on screen.
  • BarcodeScannerSwift - An iOS application that captures video from the camera, scans for barcodes and displays results on screen, completely rewritten in Swift.

Kudos

  • cwalcott initial creator of this project
  • neacao for his unparalleled support lately
  • claybridges for all the help regarding the project move

License

ZXingObjC is available under the Apache 2.0 license.

zxingify-objc's People

Contributors

alexandreos avatar andrebraga avatar arvincheung avatar benjohnde avatar carlonluca avatar chetcutisilvan avatar chriskeyring avatar cwalcott avatar dehnhard avatar grzesiekko avatar grzesiekp avatar hyukhur avatar josh- avatar jschmitt3 avatar kenstir avatar marcelofabri avatar marioradonic avatar mattjgalloway avatar michaelkirk avatar monoqlo avatar mrako avatar nakiostudio avatar neacao avatar paschmid avatar philippec avatar reednj avatar schoosch avatar sveltema avatar tomwhipple avatar valcapri avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

zxingify-objc's Issues

Code 39 generated by ZXCode39Writer is horizontally flipped (mirrored)

As in the original JAVA sources, the image representing a Code 39 is horizontally flipped.

The code can be read both ways because of the asymmetrical '*' character at the beginning and at the end but all the other generators I have tried produce a code legible from left to right.

In order to have this direction, I have made the following changes in ZXCode39Writer.m :

  • line 67, changed the order of the loop
    from
    for (int i = length - 1; i >= 0; i--) {
    to
    for (int i = 0; i < length; i++) {
  • line 81, changed the order of each character parsing
    from
    int temp = a & (1 << i);
    to
    int temp = a & (1 << (8- i));

PDF417 not scanning

This is actually the same as issue #28. I can scan several 1d barcodes, however when scanning a PDF417 formatted 2d barcode, it never scans. I've included a photo of the PDF417 I'm trying to scan.
photo

Some strings encoded as PDF417s are corrupted or not readable

I'm building an iPhone app that needs to encode (i.e., create or generate) either a PDF417 or Aztec barcode. I've got ZXingObjC generating PDF417s, but the barcodes it creates from certain strings are either corrupted or unreadable.

Here is the code I'm using to test the SDK... this is from the demo code:

    barcodeText = @"BEHAN/MAX";

    NSError* error = nil;
    ZXMultiFormatWriter* writer = [ZXMultiFormatWriter writer];
    ZXBitMatrix* result = [writer encode:barcodeText
                                  format:kBarcodeFormatPDF417
                                   width:528
                                  height:216
                                   error:&error];

    NSString* errorMessage = [error localizedDescription];
    NSLog(@"%@", errorMessage);
    NSLog(@"%@", barcodeText);


    if (result) {
        // CGImageRef image = [[ZXImage imageWithMatrix:result] cgimage];
        self.barcodeResult.image = [UIImage imageWithCGImage: [[ZXImage imageWithMatrix:result] cgimage]];

        // This CGImageRef image can be placed in a UIImage, NSImage, or written to a file.
    } else {
        self.barcodeResult.image = nil;
    }

I use this code to generate a PDF14 on the screen of one iPhone, and then read the output with a barcode scanner.

Here are various test strings, and what is read:

 '123456789'      ->  '123456789'     good
 'abcde fghij'    ->  'abcde fghij'   good

 'BEHAN/MAX'      ->  'BEHAN$'        bad 
 'M1ABC'          ->  'M0'            bad
 'UUP2E28'        ->  'UUP1>'         bad
 'ABCDE FGHI2XYZ' ->  'ABCDE FGHI2#-' bad

Anything long, like the text encoded on an airline boarding pass, is not readable, at all.

'M1BEHAN/MAX           E28UUP2 BHXDUBEI 0263 220Y006A0021 10'     not readable 

Some codes are readable, but it's not hard to find examples that don't work. Pretty much anything with uppercase characters and numbers don't work.

For issue #42, you say to use UTF16 characters, but encode: takes an NSString... Not sure how UTF16 comes into it. Can you explain, please?

The start of a session is pretty slow more than 3 sec on a iPhone3GS

Using the library I've seen that the start of the session is pretty slow more that 3 sec on iP3GS. Digging into the code I've seen a lot of customized getter that instanciate lazily some objects. In my benchmarks doing a photo application I've seen that starting a session is a lot faster If we provide a default set of options inside a "session block" instead of instantiate them lazily, that is because every time we made a change on a session the system automatically open and commit a configurations block.
I'm pretty sure that it will be a lot faster in that way.
Hope this helps

Buid Failed

Besides the Frameworks referenced in the 3rd step, "CoreMedia.framework", "AVFoundation.framework" and "CoreVideo.framework" should also be added in the "Link Binary With Libraries".

Correction for VLA warning on static analyzer (ZXQRCodeDecoder.m)

The static analyzer gives a variable length array warning, seeing totalBytes as zero. This can be corrected adding a small check and it will ensure that the method returns nil if totalBytes is really zero (although this is probably extremely unlikely). Diff below:

@@ -110,21 +110,25 @@
     totalBytes += dataBlock.numDataCodewords;
   }

-  unsigned char resultBytes[totalBytes];
-  int resultOffset = 0;
-
-  for (ZXQRCodeDataBlock *dataBlock in dataBlocks) {
-    NSMutableArray * codewordBytes = [dataBlock codewords];
-    int numDataCodewords = [dataBlock numDataCodewords];
-    if (![self correctErrors:codewordBytes numDataCodewords:numDataCodewords error:error]) {
-      return nil;
-    }
-    for (int i = 0; i < numDataCodewords; i++) {
-      resultBytes[resultOffset++] = [[codewordBytes objectAtIndex:i] charValue];
+  if ( totalBytes > 0 ) {
+    unsigned char resultBytes[totalBytes];
+    int resultOffset = 0;
+    
+    for (ZXQRCodeDataBlock *dataBlock in dataBlocks) {
+      NSMutableArray * codewordBytes = [dataBlock codewords];
+      int numDataCodewords = [dataBlock numDataCodewords];
+      if (![self correctErrors:codewordBytes numDataCodewords:numDataCodewords error:error]) {
+        return nil;
+      }
+      for (int i = 0; i < numDataCodewords; i++) {
+        resultBytes[resultOffset++] = [[codewordBytes objectAtIndex:i] charValue];
+      }
     }
+    
+    return [ZXQRCodeDecodedBitStreamParser decode:resultBytes length:totalBytes version:version ecLevel:ecLevel hints:hints error:error];
   }
-
-  return [ZXQRCodeDecodedBitStreamParser decode:resultBytes length:totalBytes version:version ecLevel:ecLevel hints:hints error:error];
+  
+  return nil;
 }

EXC_BAD_ACESS in dealloc

I am getting EXC_BAD_ACESS on [session removeInput:input]; in ZXCapture.m during dealloc. This is on an iPhone 4 running iOS 5 and iOS 6.0. Refactoring to ARC did not resolve the crash. The crash happens after popping the view controller, following about 1 second delay.

  • (void)dealloc {
    if (input && session) {
    [session removeInput:input];
    }

Crash during startup

Hi, I'm trying to add the library into my project.

I was trying to test the library with the sample code, but as soon as the [self.capture start]; is called, I receive a crash of EXC_BAD_ACCESS that backtraces to this:

  • thread #1: tid = 0x1c03, 0x37ba7e3c libobjc.A.dylibobjc_release + 12, stop reason = EXC_BAD_ACCESS (code=1, address=0x13) frame #0: 0x37ba7e3c libobjc.A.dylibobjc_release + 12

Does this have anything to do with my project using ARC ?

Ok, further investigation points to the crash reason being the Autorelease pool drain call.
Any hints on why ?

Problems with OS X Program

I can't figure out for the life of me how to add the framework to my osx project in Xcode 4.5.2. I followed the instructions in the readme (though I never saw any option for "Reference Type" is "Relative to Project"), but when I add #import <ZXingObjC/ZXingObjC.h> to my AppDelegate, xcode can't find the file. The iOS example projects that you provide, however, compile fine. My apologies for asking such a noobish question, I just wrestled with this for quite a while and can't seem to figure it out.

Landscape?

I have successfully implemented the ZXingObjC framework into my app. How do I code the camera or the capture layer to support rotation to landscape in my ViewController?
Thanks!

How to save the scaned image.

scanning the all types of barcode images using video mode ,but unable to capture the image.
in ZXCGimageLuminous class there is a method which calls a object
CGImageRef result = CGBitmapContextCreateImage(newContext);
but the result is null

ZXDataMatrixEncoder.h not found

I'm trying to integrate the new version of the framework but everything I try, I got the same result:
Build error : ZXDataMatrixEncoder.h not found

Could it be missing files being not added to framework during compilation?

Memory Leak

Hi,

There is a retaining cycle between ZXModulusGF and ZXModulusPoly.

This not only causes leaks on them, but it also causes leaks on ZXPDF417ECErrorCorrection's field property. This leak in particular comes from the class method PDF417_GF of ZXModulusGF.

After some analysis, I believe the problem can be fixed by changing the ZXModulusPoly's field property to assign (not retaining, and so breaking the cycle).

I'm not fully familiar with the code, so I'm not sure that there is no place else where ZXModulusPoly's field needs to be retained. If it does, than the bug can't be fixed as I suggest.

ZXCapture gets stuck on one camera

I stumble on this bug, here whenever I used one camera and was unable to set the other camera if I stopped ZXCapture. Some thing like (in pseudo Objective-C)
.. [zxCaptureInstance setCamera:back]
.. [zxCaptureInstance start]
.. [zxCaptureInstance stop]
.. [zxCaptureInstance setCamera:front]
.. [zxCaptureInstance start]
will continue to capture from the back camera.

After some debugging, I was able to fix it at ZXCapture's setCamera: instance method. In this method I removed the if clause bellow (line 641)
.. if (running) {
.... [self replaceInput];
.. }
and left a simple call to replaceInput,
.. [self replaceInput];

I must warn, however, that this is a workaround and I do not know if it's the best solution. If I find any harming effects I'll let you know. But by the analysis I've done so far, there is no reason for it to be harmful.

Memory leak ZXBinaryBitmap and ZXQRCodeReader.

I think there is a memory leak at ZXBinaryBitmap and ZXQRCodeReader.

Im capturing video frames as in http://developer.apple.com/library/ios/#qa/qa1702/_index.html.

And after acquire a 'CGImageRef' I crop the image to select the area that should contain the code. Finally delegate ZXingObjC to decode the image:

ZXLuminanceSource* source = [[ZXCGImageLuminanceSource alloc] initWithCGImage:image];
ZXBinaryBitmap* bitmap = [ZXBinaryBitmap binaryBitmapWithBinarizer:[ZXHybridBinarizer binarizerWithSource:source]];

NSError* error = nil;
ZXResult* result = [self.reader decode:bitmap hints:self.hints error:&error];

if i use 'setSampleBufferDelegate:queue' in a main queue works fine, but my animeted button on the screen looks very lagged. After create a new queue the leak appeared.

Reducing the frame rate i'm able to execute

ZXBinaryBitmap* bitmap = [ZXBinaryBitmap binaryBitmapWithBinarizer:[ZXHybridBinarizer binarizerWithSource:source]];

But the leak remains in ZXQRCodeReader's decode:hints:error: method

trouble with PDF417 codes

I'm having trouble getting PDF417 codes to scan at all. Has anyone had success in reading in PDF417 codes? Or is it just me?

Thanks,
-Dan.

ISSN support

I realize this is most likely an issue with ZXing proper and not your port but I thought it best to start here. Many magazines have ISSN barcodes on them. ISSN barcodes seem to be EAN barcodes followed by a two digit issue number. Using ZXingObjC I am able to scan the EAN portion of these ISSN numbers just fine. However, it would be nice to also be able to scan the complete ISSN code, including issue number.

BTW - thank you very much for this library. I had been using the ZBar scanner in my app. I recently replaced that with your library and it works much better. Scans using an iPad 2 are MUCH more successful than before. My customers will be happy. Thanks.

What do I need to do to get a sample buffer ---> bitmap for reader.decode ?

Do you have a real wiki or user' group to ask questions, or is it best to just create an issue and hope someone will respond?

I'm still banging my head on this, trying to put together a clean interface to ZXing to just decode QR Codes (and ignore the other bar codes).

I thought I had something that worked, but it seems I'm shooting myself in the foot as it crashes.

The main ZXing library, seems to have a much simpler insertion point, to take a video frame or image, and attempt to decode it. I'm not an expert on using AVSession, the preview layer, or CGImages (yet!), so if there's a simple way to QUICKLY take a buffer (currently setting mode to

code snippet from an Android app:

    LuminanceSource lsource = new PlanarYUVLuminanceSource(params[0], _width, _height, 0, 0, _width, _height, false);
    BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(lsource));
    QRResult res = null;
    try
    {
        QRCodeReader reader = new QRCodeReader();
        Result result = reader.decode(bitmap, null);

code snippet from ZXing ZXingWidgetController.m:

UIImage *scrn = [[UIImage alloc] initWithCGImage:newImage];
CGImageRelease(newImage);
Decoder *d = [[Decoder alloc] init];
d.readers = readers;
d.delegate = self;
cropRect.origin.x = 0.0;  
cropRect.origin.y = 0.0;
decoding = [d decodeImage:scrn cropRect:cropRect] == YES ? NO : YES;

my code snippet(s):

In the AVSession setup:

output.videoSettings =
[NSDictionary dictionaryWithObject:
 [NSNumber numberWithInt:kCVPixelFormatType_32BGRA]
                            forKey:(id)kCVPixelBufferPixelFormatTypeKey];
     _reader = [[ZXQRCodeReader alloc] init];

In the captureOutput delegate:

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection {
@autoreleasepool {
    CVImageBufferRef videoFrame = CMSampleBufferGetImageBuffer(sampleBuffer);
        CGImageRef videoFrameImage = [ZXCGImageLuminanceSource createImageFromBuffer:videoFrame];
        CGImageRef rotatedImage = [self rotateImage:videoFrameImage degrees:rotation];

      // ***** It crashes on  the initWithCGImage ....     
        ZXCGImageLuminanceSource *source = [[ZXCGImageLuminanceSource alloc] initWithCGImage:rotatedImage];
        ZXHybridBinarizer *binarizer = [[ZXHybridBinarizer alloc] initWithSource:source];
        ZXBinaryBitmap *bitmap = [[ZXBinaryBitmap alloc] initWithBinarizer:binarizer];

        NSError *error;
        ZXResult *result = [self.reader decode:bitmap hints:nil error:&error];

        [self setupImage:sampleBuffer];
        if (result) {
                [self captureResult:result];
    }
}
}

I'm obviously missing one or two key elements, and am pulling my hair out at the moment.... help!

I think it works if I don't rotate the image, but unfortunately the image is then rotated and the points for the QR Code do not match up right. The rotate Image code is lifted directly from ZXCapture.m

Better check for AVCaptureSessionPresetiFrame960x540 on iOS 4.3 (ZXCapture.m)

The check for AVCaptureSessionPresetiFrame960x540 may be problematic on iOS 4.3. While checking for NSOrderedSet to see if we are on iOS 5.0 or later may seem enough, it is better to check if AVCaptureSessionPresetiFrame960x540 constant is defined. As it is not defined on iOS 4.3, this may lead to a crash.

Here is a diff for the check:

@@ -233,6 +233,7 @@ static bool isIPad();
           NSClassFromString(@"NSOrderedSet") && // Proxy for "is this iOS 5" ...
           [UIScreen mainScreen].scale > 1 &&
           isIPad() &&
+          &AVCaptureSessionPresetiFrame960x540 != nil &&
           [zxd supportsAVCaptureSessionPreset:AVCaptureSessionPresetiFrame960x540]) {
         // NSLog(@"960");
         preset = AVCaptureSessionPresetiFrame960x540;

Can't scan PDF417

When I try scanning a barcode with format PDF417 it doesn't work.. the only feedback I get is an exception..

2013-03-20 21:19:52.368 BarcodeScanner[3219:907] * Terminating app due to uncaught exception 'NSRangeException', reason: '* -[__NSArrayM replaceObjectAtIndex:withObject:]: index 952 beyond bounds [0 .. 928]'
*** First throw call stack:
(0x39cdb2a3 0x325fa97f 0x39c267d9 0xc42e7 0xc3d69 0xc6625 0xcec29 0xf20d9 0xf0e79 0x652e9 0x341a2173 0x32e9311f 0x32e924b7 0x32e971bd 0x39caef3b 0x39c21ebd 0x39c21d49 0x35b5b2eb 0x36bb3301 0x49783 0x49710)
libc++abi.dylib: terminate called throwing an exception

ZXingObjC Support

Hi,

Can you please inform which Bar Code versions does ZXingObjC Supports.

It seems i am able to read some codes but some odes give format error.

Thanks
Azeem

iOS archive issue: 'ZXingObjC/ZXingObjC.h' file not found

I followed the instructions in the readme file and it worked fine when I ran it as debug config on simulator or device, then when I archived, got this error:

'ZXingObjC/ZXingObjC.h' file not found

tried to set header search path in build settings as something like ./libs/ZXingObjC-8f83c0b then got an error

libs/ZXingObjC-8f83c0b/ZXingObjC/ZXingObjC.h:20:9: 'ZXingObjC/ZXAztecDecoder.h' file not found

any idea how to fix it? thanks

BarcodeScanner sample seems not working

Hello,
Just downloaded the source and tried the BarcodeScanner, but unfortunately I can't make it work on device, something is not working in dependencies

undefined symbols for architecture armv7s:
"OBJC_CLASS$_ZXCapture", referenced from:
objc-class-ref in ViewController.o
ld: symbol(s) not found for architecture armv7s
clang: error: linker command failed with exit code 1 (use -v to see invocation)

On simulator builds fine.

Thanks,
Andrea

Error while building iOS Framework

Hello,

Thank you for your great porting work!
I want to report an error while building target iOS Framework. I got:

** BUILD SUCCEEDED **

lipo: can't open input file: /Users/sugarwaterbros/Library/Developer/Xcode/Deriv
edData/ZXingObjC-cwuhphtnmfukhwhgryzxlxgfwdbe/Build/Products/Debug-iphonesimulat
or/libZXingObjC.a (No such file or directory)
Showing first 200 notices only
Command /bin/sh failed with exit code 1

I read shell script in Build Setting>Build Framework and I fixed:

--- build-a.txt 2012-12-04 01:28:28.000000000 +0900
+++ build-b.txt 2012-12-04 01:27:54.000000000 +0900
@@ -9,7 +9,7 @@
 export SF_MASTER_SCRIPT_RUNNING=1

 SF_TARGET_NAME=${PROJECT_NAME}
-SF_EXECUTABLE_PATH="lib${SF_TARGET_NAME}.a"
+SF_EXECUTABLE_PATH="lib${SF_TARGET_NAME}-iOS.a"
 SF_WRAPPER_NAME="${SF_TARGET_NAME}.framework"

 # The following conditionals come from

Build has succeeded. Is this right ?
I built the target with Xcode 4.2 /MacOS X 10.6.8, should update...

Thanks,

Yasuhiro Sugawara

PDF417 Barcode on Front Camera (iPad)

Hi,

Thank you for the making this great library available!

I was able to use the rear camera to scan a PDF417 barcode successfully on an iPad2. However, the front camera seems to have an issue. The front camera displays items as a mirror image which may be leading to issues in processing it successfully. I have attempted to insert the following code in ZXCapture.m to no avail in an effort to correct the issue:

In the (ZXCaptureDevice *)device procedure I put in the following to fix the display mirroring (visual only):

AVCaptureDevicePosition position = AVCaptureDevicePositionBack;
if (camera == self.front) {
position = AVCaptureDevicePositionFront;
transform = CGAffineTransformScale(CGAffineTransformIdentity, -1, 1); // Mirror image for Front Camera
}

In the captureOutput: procedure I inserted the following:

CGImageRef videoFrameImage = [ZXCGImageLuminanceSource createImageFromBuffer:videoFrame];
CGImageRef rotatedImage = [self rotateImage:videoFrameImage degrees:rotation];

CGFloat imageWidth = CGImageGetWidth(rotatedImage);
CGFloat imageHeight = CGImageGetHeight(rotatedImage);

CGRect bounds = CGRectMake(0, 0, imageWidth, imageHeight);

CGAffineTransform imageTransform = CGAffineTransformMakeTranslation(CGImageGetWidth(rotatedImage), 0.0);
imageTransform = CGAffineTransformScale(transform, -1.0, 1.0);

UIGraphicsBeginImageContext(bounds.size);

CGContextRef context = UIGraphicsGetCurrentContext();
CGContextScaleCTM(context, 1.0, -1.0);
CGContextTranslateCTM(context, 0, -imageHeight);

CGContextConcatCTM(context, imageTransform);
CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, imageWidth, imageHeight), rotatedImage);
UIGraphicsEndImageContext();

ZXCGImageLuminanceSource *source
= [[[ZXCGImageLuminanceSource alloc]
initWithCGImage:rotatedImage]
autorelease];

Theoretically, this was to mirror and save the CGImage to help with the processing, but didn't appear to have any effect.

I also tried to set self.capture.mirror = TRUE; but that had no effect as well.

Any insight into the issue would be very much appreciated. Thanks!

Does not support ARC

I meet a problem that ZXingObjc doesn't support ARC but my project does, so there is a conflict.
My solution is changing the Compiler Flags of each file in ZXingObjc to -fno-objc-arc. Since there are so many files in this project, it really makes me crazy. Any other ideas? Or can it be changed to support ARC in next version?

Incompatible Warning

Line 172 in ZXDataMatrixErrorCorrection.m (version: 0c0cc1d),
eccReversed[numECWords] = NULL;
causes a warning saying
Incompatible pointer to integer conversion assigning to 'unichar' (aka 'unsigned short') from 'void *'
Maybe it should be changed to
eccReversed[numECWords] = 0;

captureOutput:didOutputSampleBuffer:fromConnection Can not be stopped by stop method

Im trying to stop captureOutput:didOutputSampleBuffer:fromConnection method by [self.capture stop]
, where capture is an instance of ZXCapture class. After using Instrument to do time profile, I find that
the following method in ZXCapture.m is running all the time even I called the method [self.capture stop].
I know hard_stop will do the job, but when it called, the [self.capture start] will not work not.

  • (void)captureOutput:(ZXCaptureOutput_)captureOutput
    ZXQT(didOutputVideoFrame:(CVImageBufferRef)videoFrame
    withSampleBuffer:(QTSampleBuffer_)sampleBuffer)
    ZXAV(didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer)
    fromConnection:(ZXCaptureConnection*)connection {}

Any help will be appreciated!

How to select which bar codes to look for...

It would seem that if we know we ONLY want to look at QR codes, we ought to be able to specify that, or a bitmask with the barcode types we want to examine. I would think it would speed up the processing.

Is there a way to select which codes to examine instead of checking for everything and (if everything is working fine) find the right barcode type? I my case, I have an app which ONLY wants to look at QR Codes.

Thanks.

Storyboard example

Hi, thanks for the Great Code, Can you please add a storyboard example with a navigation control.
Thanks

Code 39

the code39 generated by ZXCode39Writer cannot be read.

it seems that there is no space between the different characters in the barcode.

The narrowWhite array should contains {1}, not {0}.

I changed the code at line 63 to fix this issue :
int narrowWhite[narrowWhiteLen] = {1};
instead of
memset(narrowWhite, 0, narrowWhiteLen * sizeof(int));

Tag new version

Hi,

nice work and thanks for sharing your ZXing work this way.

I currently create a CocoaPods spec file for your project, i hope thats fine for you?

Because the v2.0 tag is broken, could you tag a new version v2.0.1 or something?

This fix is required to build project with ZXing without hacks:

TheLevelUp/ZXingObjC@9c60222

http://cocoapods.org/

Thanks and best regards,

Christoph Jerolimov

dismissviewcontroller:aimated:completion: in captureresult:result: crashes app

i started integrating zxingobjc into my app by using the example code and it works well, but I want to dismiss the Scanner view controller when I actually get a result while scanning, so I stop the capture and call dismissviewcontroller:animated:completion, but right after the controller is dismissed, the app crashes.

i get some messages from libobjc.A.dylib`objc_msgSend: which i don't understand, but I guess it might be a threading error. not sure though.

i also tried making sure to dismiss from the main thread, but it didn't help. is this a known issue and do you have any tips for me as how to dismiss the scanner view controller correctly when it got a result?

QR Code Read Issue

Hello I am using qr code library to generate and read qr code. At first I was getting Memory warning(crash) from my app and I solved this issue with this

to make it work (from the version downloaded on september 20th 2012) :

In ZXingObjC/client/ZXCapture.m

modify line 107 : [NSMakeCollectable(rotatedImage) autorelease];
comment line 499 : // CGImageRelease(videoFrameImage);
comment line 506 : // CGImageRelease(rotatedImage);
In ZXingObjC/client/ZXCGImageLuminanceSource.m

comment line 238 : // CGImageRetain(image);
In ZXingObjC/common/ZXHybridBinarizer.m :

add this at line 79 : free(_luminances);

But now I have different issue. When I try to read qr code, app try to read it twice. I don't know why but if app read qr code once app slow down until read the second time.

Sorry It was my mistake. I solve the problem. Library is working fine.

Specific PDF417 barcode crashes library

When I scan this barcode:
_P417BAR

The library crashes my app with. The console outputs the following:

2013-02-24 18:40:05.340 PasPas[1396:907] *** -[AVCaptureVideoDataOutput setVideoSettings:] - videoSettings dictionary contains one or more unsupported (ignored) keys: (
    Height,
    Width
)
2013-02-24 18:40:10.572 PasPas[1396:907] *** Terminating app due to uncaught exception 'NSRangeException', reason: '-[__NSCFString replaceCharactersInRange:withString:]: Range or index out of bounds'
*** First throw call stack:
(0x31b653e7 0x39856963 0x31b65307 0x31b34a57 0x16fd29 0x16ec63 0x170789 0x178f17 0x19b381 0x19a121 0x11dc81 0x30cf2ecb 0x39c70793 0x39c705db 0x39c73e45 0x31b391b1 0x31aac23d 0x31aac0c9 0x3568a33b 0x339c82b9 0xaa19d 0x39c83b20)
libc++abi.dylib: terminate called throwing an exception

XCode now breaks in ZXPDF417DecodedBitStreamParser on +byteCompaction:codewords:codeIndex:result: line 426. It seems that while decoding there are some assumptions made about the length of parts of the barcode that are not correct for this one.

Memory leak in ZXHybridBinarizer.m

I think that there is a memory leak in blackMatrixWithError (ZXHybridBinarizer.m) as the matrix line 63 (unsigned char * _luminances = source.matrix;) is never freed.

adding the following code on line 80 seems to work

free(_luminances);

Bug

Hi, I am developing a cocoa application (In Lion OS) where I added the ZXingObjC as per the guidelines but getting bugs as 'Lexical or Preprocessor Issue' 'ZXBarcodeFormat (ZXBitMatrix, ZXImage, ZXMultiFormatWriter) file's not found'. Can you explain me the reason behind this bugs or I am missing something. Please help me to over coe this Issue. Thanks in advance.

How to check each frame

Is there a set of methods which would allow an app which already has setup it's own AVSession and is already grabbing frame by frame video, to pass each frame one at a time to attempt a decoding, instead of using the full video streaming engine which is provided by the ZXCapture class?

I've been reviewing the code looking for the hooks to see where this is, or if it is plausible or possible without too many changes, but am coming up short so far. A pointer in the right direction would also be helpful,

Thanks.

Code 128

Hi,

I'm writting an application on iOs and I want to use your library.
i tried to display a code 128.

With code with only digits, it works fine, my barcode reader manage to read it.
But when I want to add some other characters, it doesn't works.

For example, if I want to show a barcode "1234567890*", it doesn't work.
I compared the barcode generated with the one generated online, and the problem seems to be the end of the barcode : the last bar is still missing.

the one generated with your lib : http://postimage.org/image/mdqt546g5/
the one generated with online tool : http://postimage.org/image/h6xf3mq2h/

Thanks in advanced

ZXDataMatrixBitMatrixParser.m init method leaks

- (id)initWithBitMatrix:(ZXBitMatrix *)bitMatrix error:(NSError**)error
method leaks when the dimensions are not valid. The object is alloc'ed, but without being init'ed, it returns nil, hence leaks the 16 bytes necessary for alloc'ing an object. The correct method should be the following:
- (id)initWithBitMatrix:(ZXBitMatrix *)bitMatrix error:(NSError**)error {
  if (self = [super init]) {
    int dimension = bitMatrix.height;
    if (dimension < 8 || dimension > 144 || (dimension & 0x01) != 0) {
      if (error) *error = FormatErrorInstance();
      [self release];
      return nil;
    }
    
    self.version = [self readVersion:bitMatrix];
    if (!self.version) {
      [self release];
      if (error) *error = FormatErrorInstance();
      return nil;
    }
    self.mappingBitMatrix = [self extractDataRegion:bitMatrix];
    self.readMappingMatrix = [[[ZXBitMatrix alloc] initWithWidth:mappingBitMatrix.width
                                                          height:mappingBitMatrix.height] autorelease];
  }
  
  return self;
}

Locks during ZXResult

I seem to also be having a problem where everything stalls during ZXResult. I thought originally it was due to me noodling the code to get the project to compile correctly. But now, using this new version, it still stalls. Here's what I'm implementing. It never reaches the NSLog(@"5"); It stops somewhere inside ZXResult.

Note, targetMovieFrame is a CGImageRef that was working fine with ZXing.

NSLog(@"1");
ZXLuminanceSource* source = [[[ZXCGImageLuminanceSource alloc] initWithCGImage:targetMovieFrame] autorelease];
ZXBinaryBitmap* bitmap = [ZXBinaryBitmap binaryBitmapWithBinarizer:[ZXHybridBinarizer binarizerWithSource:source]];
NSLog(@"2");
NSError* error = nil;
// There are a number of hints we can give to the reader, including
// possible formats, allowed lengths, and the string encoding.
ZXDecodeHints* hints = [ZXDecodeHints hints];
NSLog(@"3");
ZXMultiFormatReader* reader = [ZXMultiFormatReader reader];
NSLog(@"4");
ZXResult* result = [reader decode:bitmap hints:hints error:&error];
NSLog(@"5");
if (result)
{
// The coded result as a string. The raw data can be accessed with
// result.rawBytes and result.length.
NSString* contents = result.text;

    // The barcode format, such as a QR code or UPC-A
    ZXBarcodeFormat format = result.barcodeFormat;

    NSLog(@"Content = %@", contents);

    return contents;

}
else
{
NSLog(@"Did not find content in QRCode.");
return 0;
// Use error to determine why we didn't get a result, such as a barcode
// not being found, an invalid checksum, or a format inconsistency.
}

Updates to README

Of note, using latest XCode versions, this may save a lot of people some headaches.

  1. In the ZXingObjC project, make the headers available for importing to your project.
    -- Select the ZXingObjC project, under "Build Settings" locate "Public Headers Folder Path"
    -- Enter "$(TARGET_NAME)" in the field.
If you are using ZXingObjC as a binary library, you may also want to set the directory where the library files are built.
-- Select the ZXingObjC project, under "Build Settings" locate "Installation Directory"
-- Enter "$(BUILT_PRODUCTS_DIR)" in the field.
  1. In your project, make the headers of the library findable.
    -- Select the project, under "Build Settings" locate "User Header Search Paths"
    -- Enter "$(BUILT_PRODUCTS_DIR)" in the field.
  2. Now, you can import the library headers, just like any other framework:

    import ... (can't put angle brackets in the text) ...

Correction for VLA warning on static analyzer (ZXDataMatrixDecoder.m)

The static analyzer gives a variable length array warning, seeing totalBytes as zero. This can be corrected adding a small check and it will ensure that the method returns nil if totalBytes is really zero (although this is probably extremely unlikely). Diff below:

@@ -91,21 +91,26 @@
   for (int i = 0; i < dataBlocksCount; i++) {
     totalBytes += [[dataBlocks objectAtIndex:i] numDataCodewords];
   }
-  unsigned char resultBytes[totalBytes];
-
-  for (int j = 0; j < dataBlocksCount; j++) {
-    ZXDataMatrixDataBlock * dataBlock = [dataBlocks objectAtIndex:j];
-    NSMutableArray * codewordBytes = dataBlock.codewords;
-    int numDataCodewords = [dataBlock numDataCodewords];
-    if (![self correctErrors:codewordBytes numDataCodewords:numDataCodewords error:error]) {
-      return nil;
-    }
-    for (int i = 0; i < numDataCodewords; i++) {
-      resultBytes[i * dataBlocksCount + j] = [[codewordBytes objectAtIndex:i] charValue];
+  
+  if ( totalBytes > 0 ) {
+    unsigned char resultBytes[totalBytes];
+    
+    for (int j = 0; j < dataBlocksCount; j++) {
+      ZXDataMatrixDataBlock * dataBlock = [dataBlocks objectAtIndex:j];
+      NSMutableArray * codewordBytes = dataBlock.codewords;
+      int numDataCodewords = [dataBlock numDataCodewords];
+      if (![self correctErrors:codewordBytes numDataCodewords:numDataCodewords error:error]) {
+        return nil;
+      }
+      for (int i = 0; i < numDataCodewords; i++) {
+        resultBytes[i * dataBlocksCount + j] = [[codewordBytes objectAtIndex:i] charValue];
+      }
     }
+    
+    return [ZXDataMatrixDecodedBitStreamParser decode:resultBytes length:totalBytes error:error];
   }
-
-  return [ZXDataMatrixDecodedBitStreamParser decode:resultBytes length:totalBytes error:error];
+  
+  return nil;
 }

Crash unsupported videoSettings

On iPad Mini (iOS 6.1.3):

*** -[AVCaptureVideoDataOutput setVideoSettings:] - videoSettings dictionary contains one or more unsupported (ignored) keys: (
Height,
Width
)

Compiling issues

I'm trying to compile this as is, and I'm getting a few errors. I'm getting a giant pile of "implicit conversion loses integer precision." Almost a hundred.

But a bigger issues I'm finding is "expression is not an integer constant expression" for:

ZXingObjC/oned/ZXCode128Writer.m

const unichar ESCAPE_FNC_1 = '\u00f1';
const unichar ESCAPE_FNC_2 = '\u00f2';
const unichar ESCAPE_FNC_3 = '\u00f3';
const unichar ESCAPE_FNC_4 = '\u00f4';

Trying to figure out what the issue is, but wondering if anyone else is having some issues compiling this. I'm running 10.8, new version of XCode 4. 64bit.

Capture session never really stops

Hello,
I use ZXing in IOS application and I try to read some kinds of barcodes, successfully, but when one of them is read, I need to go back to my application.
Whatever I try to do, I can't stop the capture so my application is VERY VERY VERY slow.
Even the smallest ScrollView has not enough resources to manage bounds animations.
I'll try to destroy session but I think it would be a great thing to offer a way to get out of scanner.

Generating PDF417 barcodes - there is an extra character in the generated code

Hi there,

I'm generating PDF417 barcodes. The problem is that in the result there is an extra character, for example if you try to generate a code from this sequence: XI005016788760, and you are scanning the generated code the result will be XI005016788760]. So there is an extra "]" at the end. I've tried with multiple scanners, the result is the same, so I think the problem is with the generation itself.

How to stop or pause live video at the point of capture?

Not sure where to post to ask questions, and other github projects have said open an issue, so here goes...

Is there an "easy" method to call to stop or pause the live video leaving the last frame (or the next frame?) on screen, so the image that was recognized would/could be saved or visible?

I've looked through the code, but haven't found anything quite yet.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.