Как я могу заархивировать несколько изображений в моем приложении - PullRequest
0 голосов
/ 14 октября 2011

В моем приложении я использую камеру, чтобы сделать несколько снимков.Эти фотографии необходимо отправить за один раз.По этой причине я пытаюсь реализовать функцию сжатия фотографий, которые я сделал.

Я искал в Интернете несколько библиотек, которые я мог бы использовать в своем проекте.Я выпустил Objective Zip (http://code.google.com/p/objective-zip/wiki/GettingStarted). Однако мне удалось только сжать (или распаковать) текстовые файлы. Но сжатие (или распаковка) фотографий не упоминается.

Мне удалосьс преобразованием моей фотографии токена в объект NSData. Теперь я хочу сжать их в Zip-файл. Есть ли кто-нибудь, кто имел опыт работы с такими функциями.

Помощь очень ценится!

Редактировать

Я сейчас использую библиотеку Objective Zip, но мое приложение продолжает падать. По-прежнему получаю известную ошибку "Поток 1: Программа получила сигнал:" SIGARBT "". Япытаясь сжать одно изображение, которое я сделал камерой, и сохранить в каталоге документов.

Внутри фрагмента вы можете видеть, что я вызываю фотографию, которую я сделал, и архивирую ее методом ZipFile.отправляю мой zip-файл в виде вложения электронной почты.

Вот фрагмент моего кода:

-(IBAction)sendID{



    NSString *docDir3 = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

    NSString *docDir4 = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

    NSString *pngFilePath3 = [NSString stringWithFormat:@"%@/photo.png",docDir3];

    // Create the zip file
    ZipFile *zipFile = [[ZipFile alloc] initWithFileName:docDir4 mode:ZipFileModeCreate];

    // Read the files in the data directory
    NSError *error = nil;
    NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:pngFilePath3 error:&error];

    //ZipWriteStream *stream1= [zipFile writeFileInZipWithName:@"abc.txt" fileDate:[NSDate //dateWithTimeIntervalSinceNow:-86400.0] compressionLevel:ZipCompressionLevelBest];


    // Write each file to our zip
    for (NSString *filename in files) {

        // Write the file
        ZipWriteStream *stream = [zipFile writeFileInZipWithName:filename compressionLevel:ZipCompressionLevelBest];

        NSData *data = [NSData dataWithContentsOfFile:pngFilePath3];

        [stream writeData:data];

        [stream finishedWriting];
    }

    // Close the zip file
    [zipFile close];

    NSData *data = [NSData dataWithContentsOfFile:@"Test.zip"];
    MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
    picker.mailComposeDelegate=self;

    //NSData *imageData = UIImageJPEGRepresentation(viewImage, 1);

    [picker addAttachmentData:data mimeType:@"application/zip" fileName:@"Test.zip"];

    Class mailclass = (NSClassFromString(@"MFMailComposeViewController"));
    if([mailclass canSendMail]){
        [self presentModalViewController:picker animated:YES];
    }
}

Надеюсь, кто-нибудь может мне помочь.

Ответы [ 3 ]

2 голосов
/ 27 июня 2013

Я знаю, что это старая ветка, но вот как я заархивирую несколько файлов с помощью Objective-Zip:

- (NSString*) objectiveZip:(NSArray*)passedFiles
{
    NSString *outputPath = [self getOutputDirectory];

    NSString *zipFileName = @"MyZip.zip";

    outputPath = [outputPath stringByAppendingString:zipFileName];

    //Create a zip file for writing
    ZipFile *zipFile= [[ZipFile alloc] initWithFileName:outputPath mode:ZipFileModeCreate];

    //Add all the files, write to its stream and close it
    for(NSString *string in passedFiles)
    {
        NSString *fileName = string;

        NSLog(@"Add file to zip: %@", fileName);

        ZipWriteStream *stream1= [zipFile writeFileInZipWithName:fileName fileDate:[NSDate dateWithTimeIntervalSinceNow:-86400.0] compressionLevel:ZipCompressionLevelBest];

        [stream1 writeData:[NSData dataWithContentsOfURL:[NSURL URLWithString:info.pdfUrl]]];
        [stream1 finishedWriting];
    }

    // Close the zip file
    [zipFile close];

    return outputPath;
}
1 голос
/ 14 октября 2011

Лучшая найденная мною zip-библиотека - SSZipArchive .Дайте этому шанс.

0 голосов
/ 06 февраля 2015

NSString * temp = [[[makeZip textFieldAtIndex: 0] text] stringByAppendingPathExtension: @ "zip"];

NSString * zippedPath = [pathString stringByAppendingPathComponent: temp];

NSMutableArray * inputPaths = [[NSMutableArray alloc] init];

    for (int i=0; i<[selectedRows count]; i++) {
                 [inputPaths addObject:[pathStringstringByAppendingPathComponent:[selectedRows objectAtIndex:i]]];
        }
        if (![[NSFileManager defaultManager] fileExistsAtPath:zippedPath])
        {
        [SSZipArchive createZipFileAtPath:zippedPath withFilesAtPaths:inputPaths];
            [directoryContents addObject:temp];
            [tblview reloadData];
        }
...