我需要在图像数据中找到字节序列.我在 java上有下一个代码,但我需要在obj-c中使用相同的代码. Java的: private static int searchInBuffer(byte[] pBuf, int iBufferLen) { for(int i = 0; iiBufferLen - 7; i++) {
Java的:
private static int searchInBuffer(byte[] pBuf, int iBufferLen) { for(int i = 0; i<iBufferLen - 7; i++) { if (pBuf[i] == 'l' && pBuf[i + 1] == 'i' && pBuf[i + 2] == 'n' && pBuf[i + 3] == 'k') return (int)pBuf[i + 4]; } return -1; } public static int checkFlagInJpeg(String pFullFileName) { int iRes = -1; try { File f = new File(pFullFileName); FileInputStream is = new FileInputStream(f); int iBufferSize = 6 * 1024, iCount = 15; byte buf[] = new byte[iBufferSize]; while((is.available() > 0) && (iCount >= 0)) { int iRead = is.read(buf), iFlag = searchInBuffer(buf, iRead); if (iFlag > 0) { iRes = iFlag; break; } iCount--; } is.close(); } }
Obj-C(我的版本):
UIImage *image = [UIImage imageWithCGImage:[[[self.assets objectAtIndex:indexPath.row] defaultRepresentation] fullScreenImage]]; NSData *imageData = UIImageJPEGRepresentation(image, 1.0f); NSUInteger length = MIN(6*1024, [imageData length]); Byte *buffer = (Byte *)malloc(length); memcpy(buffer, [imageData bytes], length); for (int i=0; i < length - 1; i++) { if (buffer[i] == 'l' && buffer[i + 1] == 'i' && buffer[i + 2] == 'n' && buffer[i + 3] == 'k') NSLog(@"%c", buffer[i + 4]); } free(buffer);
我仍然不确定,我理解字节工作的所有方面,所以我需要一个帮助.
更新:
问题在于获取图像数据.在Martin R.的帮助下,我将解决方案合二为一,并获得下一个工作代码:
ALAssetRepresentation *repr = [[self.assets objectAtIndex:indexPath.row] defaultRepresentation]; NSUInteger size = (NSUInteger) repr.size; NSMutableData *data = [NSMutableData dataWithLength:size]; NSError *error; [repr getBytes:data.mutableBytes fromOffset:0 length:size error:&error]; NSData *pattern = [@"link" dataUsingEncoding:NSUTF8StringEncoding]; NSRange range = [data rangeOfData:pattern options:0 range:NSMakeRange(0, data.length)]; int iRes = -1; if (range.location != NSNotFound) { uint8_t flag; [data getBytes:&flag range:NSMakeRange(range.location + range.length, 1)]; iRes = flag; } NSLog(@"%i", iRes);
它的工作完美!再次感谢你!
NSData有一个方法rangeOfData:…您可以使用它来查找模式:NSData *pattern = [@"link" dataUsingEncoding:NSUTF8StringEncoding]; NSRange range = [imageData rangeOfData:pattern options:0 range:NSMakeRange(0, imageData.length)];
如果找到模式,请获取下一个字节:
int iRes = -1; if (range.location != NSNotFound && range.location + range.length < imageData.length) { uint8_t flag; [imageData getBytes:&flag range:NSMakeRange(range.location + range.length, 1)]; iRes = flag; }