如何将NSString转换为Ungmage for appengine blobstore

时间:2014-08-04 00:33:53

标签: ios objective-c google-app-engine google-cloud-endpoints blobstore

当我执行以下操作时,生成的图像为空

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);

我怎么能这么做?

原因

我需要将图像从iOS保存到Google blobstore。我需要在图像中包含一些元数据。当我将字符串编码为base64时,它不起作用。

这绝对是AFHTTPRequestOperationManager post multi-part request not working

的后续行动

2 个答案:

答案 0 :(得分:4)

以下是从NSString生成图像的代码..

实施此方法....

 +(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;
}

将此方法称为......

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

我希望它对你有用..

答案 1 :(得分:0)

这是我用来修复问题的UIImage类别

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

您可以修改方法以传递额外参数,如font,color,backgroundColor,如下所示:

+ (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];
}