NSImage to Base64

后端 未结 6 851
春和景丽
春和景丽 2021-01-18 06:51

I need to create a base64 string representation of an NSImage cocoa object. What\'s the best way of handling this, apple documentation seems to be a little short on the subj

6条回答
  •  醉梦人生
    2021-01-18 07:24

    An NSImage is a very abstract object. NSImage doesn't really care whether it's a raster image or a vector image; an NSImage object can even have raster, vector, and even programmatic representations all at once—it's that general.

    Before you can generate Base64 data, you must decide what you want to encode.

    The first step is to decide whether you want to encode a raster or vectors. The former is quite easy, and I'd guess it's probably what you meant. However, an NSImage could have come from a vector source, such as a PDF document.

    If you know you created the image from a raster source, you can just encode that source data.

    If it came from a vector source, you can still just encode that if you know the application on the decoding end will be able to handle it (e.g., if it's another Cocoa or Cocoa Touch app). On the other hand, if the app on the decoding end may be unable to handle vector data, then you should avoid this tactic.

    The one solution that works in all cases is to use NSBitmapImageRep to create a raster capture of the image. Lock focus on the image, then create an NSBitmapImageRep using that method, then unlock focus. Then, use representationUsingType:properties: to generate PNG (or whatever format is appropriate) data for the image. Then Base64-encode the PNG (or whatever format) data.

提交回复
热议问题