How to convert NSString to UIImage for appengine blobstore

為{幸葍}努か 提交于 2019-12-19 10:48:26

问题


when I do the following the resulting image is null

NSLog(@"string (%@) to base64NSData",object);
NSData *base64Data = [[object dataUsingEncoding:NSUTF8StringEncoding] base64EncodedDataWithOptions:0];
NSLog(@"NSData (%@) to UIImage",base64Data);
UIImage *image = [UIImage imageWithData:base64Data];
NSLog(@"my image is: %@",image);

How might I do this well?

Reason

I need to save an image from iOS to the Google blobstore. I need to include some metadata with the image. When I encode the string as base64 it does not work.

This is loosely a follow up to AFHTTPRequestOperationManager post multi-part request not working


回答1:


Here is the code for generating image from NSString..

Implement this method....

 +(UIImage *)imageFromText:(NSString *)text
 {
    UIFont *font = [UIFont systemFontOfSize:20.0];
    CGSize size = [text sizeWithAttributes:
               @{NSFontAttributeName:
                     [UIFont systemFontOfSize:20.0f]}];
      if (UIGraphicsBeginImageContextWithOptions != NULL)
        UIGraphicsBeginImageContextWithOptions(size,NO,0.0);
   else
       UIGraphicsBeginImageContext(size);

[text drawAtPoint:CGPointMake(0.0, 0.0) withFont:font];
   //    [text drawAtPoint:CGPointMake(0.0, 0.0) forWidth:CGPointMake(0, 0) withFont:font fontSize:nil lineBreakMode:NSLineBreakByWordWrapping baselineAdjustment:NSTextAlignmentCenter];

UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

 return image;
}

Call this method like...

  UIImage *image;
  image = [self imageFromText:@"Good Morning];
  //Use this image as per your requirement 

I hope it work for you..




回答2:


Here is UIImage category I used to fix my problem

http://hasseg.org/blog/post/692/use-unicode-emoji-as-icons-in-native-ios-apps/

You can modify method to pass extra parameters like font, color, backgroundColor as follows :

+ (UIImage *) hg_imageFromString:(NSString *)string withFont:(UIFont*)font textColor:(UIColor*)color andBgColor:(UIColor*)bgColor;
{
    UILabel *label = [[UILabel alloc] init];
    label.text = string;
    label.opaque = NO;

    if(bgColor != nil)
        label.backgroundColor = bgColor;

    if(color != nil)
        label.textColor = color;

    if(font != nil)
        label.font = font;
    else
        label.font = [UIFont systemFontOfSize:17.0];

    CGSize size = [string sizeWithAttributes:@{NSFontAttributeName: label.font}];

    CGSize measuredSize = CGSizeMake(ceilf(size.width), ceilf(size.height));

    label.frame = CGRectMake(0, 0, measuredSize.width, measuredSize.height);
    return [UIImage hg_imageFromView:label];
}


来源:https://stackoverflow.com/questions/25110365/how-to-convert-nsstring-to-uiimage-for-appengine-blobstore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!