从相机拍摄照片并将其显示在 UIImageView 中

发布于 2024-12-10 21:08:06 字数 2601 浏览 0 评论 0原文

我有一个包含一些字段(名称、价格、类别)和分段控件的视图,以及用于拍照的按钮。
如果我在模拟器(无相机)上尝试此操作,它可以正常工作:我可以从相机胶卷中选择图像,对其进行编辑并返回到视图,该视图将显示所有字段及其内容。
但是在我的iPhone上,当我在编辑后选择图像并返回到视图时,除了 UIImageView 之外的所有字段都是空的。
我还尝试将字段的内容保存在变量中并放入他们回到“viewWillApper”方法中,但应用程序崩溃了。
开始思考下面的方法可能有问题

编辑

我找到了解决方案此处。我为 UIImage 类定义了一个新方法。 (点击链接了解更多信息)。
然后我研究了 UIImageView 的框架,使其适应新的尺寸(横向或纵向)。

-(IBAction)takePhoto:(id)sender {
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        self.imgPicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        self.imgPicker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
    } else { 
        imgPicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    }
    [self presentModalViewController:self.imgPicker animated:YES];
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissModalViewControllerAnimated:YES];

    NSDate *date = [NSDate date];
    NSString *photoName = [dateFormatter stringFromDate:date];    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUs    erDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    imagePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png", photoName]];

    UIImage *picture = [info objectForKey:UIImagePickerControllerOriginalImage];

    // ---------RESIZE CODE--------- //
    if (picture.size.width == 1936) {
        picture = [picture scaleToSize:CGSizeMake(480.0f, 720.0f)];
    } else {
        picture = [picture scaleToSize:CGSizeMake(720.0f, 480.0f)];
    }
    // --------END RESIZE CODE-------- //

    photoPreview.image =  picture;

    // ---------FRAME CODE--------- //
    photoPreview.contentMode = UIViewContentModeScaleAspectFit;
    CGRect frame = photoPreview.frame;
    if (picture.size.width == 480) {
        frame.size.width = 111.3;
        frame.size.height =167;
    } else {
        frame.size.width = 167;
        frame.size.height =111.3;
    }
    photoPreview.frame = frame;
    // --------END FRAME CODE-------- //


    NSData *webData = UIImagePNGRepresentation(picture);
    CGImageRelease([picture CGImage]);
    [webData writeToFile:imagePath atomically:YES];
    imgPicker = nil;
}

现在我有一个新问题!如果我拍摄一张横向照片,然后尝试拍摄另一张纵向照片,应用程序就会崩溃。我必须释放一些东西吗?

I have a view with some fields (name, price, category) and a segmented control, plus this button to take picture.

If I try this on the simulator (no camera) it works properly: I can select the image from the camera roll, edit it and go back to the view, which will show all the fields with their contents .

But on my iphone, when I select the image after the editing and go back to the view, all the fields are empty exept for the UIImageView.
I also tried to save the content of the fields in variables and put them back in the "viewWillApper" method, but the app crashes.

Start to thinking that maybe there is something wrong methods below

EDIT

I found the solution here. I defined a new method to the UIImage class. (follow the link for more information).
Then I worked on the frame of the UIImageView to adapt itself to the new dimension, in landscape or portrait.

-(IBAction)takePhoto:(id)sender {
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        self.imgPicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        self.imgPicker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
    } else { 
        imgPicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    }
    [self presentModalViewController:self.imgPicker animated:YES];
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissModalViewControllerAnimated:YES];

    NSDate *date = [NSDate date];
    NSString *photoName = [dateFormatter stringFromDate:date];    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUs    erDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    imagePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png", photoName]];

    UIImage *picture = [info objectForKey:UIImagePickerControllerOriginalImage];

    // ---------RESIZE CODE--------- //
    if (picture.size.width == 1936) {
        picture = [picture scaleToSize:CGSizeMake(480.0f, 720.0f)];
    } else {
        picture = [picture scaleToSize:CGSizeMake(720.0f, 480.0f)];
    }
    // --------END RESIZE CODE-------- //

    photoPreview.image =  picture;

    // ---------FRAME CODE--------- //
    photoPreview.contentMode = UIViewContentModeScaleAspectFit;
    CGRect frame = photoPreview.frame;
    if (picture.size.width == 480) {
        frame.size.width = 111.3;
        frame.size.height =167;
    } else {
        frame.size.width = 167;
        frame.size.height =111.3;
    }
    photoPreview.frame = frame;
    // --------END FRAME CODE-------- //


    NSData *webData = UIImagePNGRepresentation(picture);
    CGImageRelease([picture CGImage]);
    [webData writeToFile:imagePath atomically:YES];
    imgPicker = nil;
}

Now I have a new issue! If I take a picture in landscape, and try to take another one in portrait, the app crashs. Do I have to release something?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

游魂 2024-12-17 21:08:06

我遇到了同样的问题,使用相机时没有编辑过的图像,您必须使用原始图像:

originalimage = [editingInfo objectForKey:UIImagePickerControllerOriginalImage];

if ([editingInfo objectForKey:UIImagePickerControllerMediaMetadata]) {
    // test to chek that the camera was used
    // especially I fund out htat you then have to rotate the photo
    ...

如果在使用相册时裁剪了它,您当然必须重新裁剪它:

if ([editingInfo objectForKey:UIImagePickerControllerCropRect] != nil) {
    CGRect cropRect = [[editingInfo objectForKey:UIImagePickerControllerCropRect] CGRectValue];
    CGImageRef imageRef = CGImageCreateWithImageInRect([originalimage CGImage], cropRect);
    chosenimage = [UIImage imageWithCGImage:imageRef]; 
    CGImageRelease(imageRef);
} else {
    chosenimage = originalimage;
}

相机的croprect信息也存在模式,您需要检查您希望它如何表现。

I had the same issue, there is no edited image when using the camera, you must use the original image :

originalimage = [editingInfo objectForKey:UIImagePickerControllerOriginalImage];

if ([editingInfo objectForKey:UIImagePickerControllerMediaMetadata]) {
    // test to chek that the camera was used
    // especially I fund out htat you then have to rotate the photo
    ...

If it was cropped when usign the album you have to re-crop it of course :

if ([editingInfo objectForKey:UIImagePickerControllerCropRect] != nil) {
    CGRect cropRect = [[editingInfo objectForKey:UIImagePickerControllerCropRect] CGRectValue];
    CGImageRef imageRef = CGImageCreateWithImageInRect([originalimage CGImage], cropRect);
    chosenimage = [UIImage imageWithCGImage:imageRef]; 
    CGImageRelease(imageRef);
} else {
    chosenimage = originalimage;
}

The croprect info is also present for the camera mode, you need to check how you want it to behave.

霓裳挽歌倾城醉 2024-12-17 21:08:06

裁剪图像我想这可能对你有帮助

UIImage *croppedImage = [self imageByCropping:photo.image toRect:tempview.frame];

CGSize size = CGSizeMake(croppedImage.size.height, croppedImage.size.width);
UIGraphicsBeginImageContext(size);

CGPoint pointImg1 = CGPointMake(0,0);
[croppedImage drawAtPoint:pointImg1 ];

[[UIImage imageNamed:appDelegete.strImage] drawInRect:CGRectMake(0,532, 150,80) ];

UIImage* result = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
croppedImage = result;

UIImageView *mainImageView = [[UIImageView alloc] initWithImage:croppedImage];

CGRect clippedRect = CGRectMake(0, 0, croppedImage.size.width,  croppedImage.size.height);

CGFloat scaleFactor = 0.5;

UIGraphicsBeginImageContext(CGSizeMake(croppedImage.size.width * scaleFactor, croppedImage.size.height * scaleFactor));
CGContextRef currentContext = UIGraphicsGetCurrentContext();

CGContextClipToRect(currentContext, clippedRect);   

//this will automatically scale any CGImage down/up to the required thumbnail side (length) when the CGImage gets drawn into the context on the next line of code
CGContextScaleCTM(currentContext, scaleFactor, scaleFactor);

[mainImageView.layer renderInContext:currentContext];

appDelegete.appphoto = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

To Crop image i think this may help you

UIImage *croppedImage = [self imageByCropping:photo.image toRect:tempview.frame];

CGSize size = CGSizeMake(croppedImage.size.height, croppedImage.size.width);
UIGraphicsBeginImageContext(size);

CGPoint pointImg1 = CGPointMake(0,0);
[croppedImage drawAtPoint:pointImg1 ];

[[UIImage imageNamed:appDelegete.strImage] drawInRect:CGRectMake(0,532, 150,80) ];

UIImage* result = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
croppedImage = result;

UIImageView *mainImageView = [[UIImageView alloc] initWithImage:croppedImage];

CGRect clippedRect = CGRectMake(0, 0, croppedImage.size.width,  croppedImage.size.height);

CGFloat scaleFactor = 0.5;

UIGraphicsBeginImageContext(CGSizeMake(croppedImage.size.width * scaleFactor, croppedImage.size.height * scaleFactor));
CGContextRef currentContext = UIGraphicsGetCurrentContext();

CGContextClipToRect(currentContext, clippedRect);   

//this will automatically scale any CGImage down/up to the required thumbnail side (length) when the CGImage gets drawn into the context on the next line of code
CGContextScaleCTM(currentContext, scaleFactor, scaleFactor);

[mainImageView.layer renderInContext:currentContext];

appDelegete.appphoto = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文