How to convert NSString to UIImage for appengine b

2020-03-30 05:46发布

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

2条回答
来,给爷笑一个
2楼-- · 2020-03-30 06:06

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..

查看更多
可以哭但决不认输i
3楼-- · 2020-03-30 06:08

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];
}
查看更多
登录 后发表回答