With Data (not NSData), in fact how actually do you make a utf8 version of a jpeg?
This line has a problem:
let mystere = trueBinary.count.base64EncodedString(
options: .lineLength76Characters)
The problem is that trueBinary
is a Data
, and trueBinary.count
is an Int
, and Int
doesn't have a base64EncodedString
method. You want this:
let mystere = trueBinary.base64EncodedString(
options: .lineLength76Characters)
As for ‘the "lineLength" concept’: you don't have to specify a line length option if you don't want to. Arguably I shouldn't have specified one in the answer you referenced in your question, because HTTP requests are not strictly MIME messages and are not subject to the MIME line length limit. You can do this instead:
let mystere = trueBinary.base64EncodedString()
Can't convert NSData to NSString when using UIImageJPEGRepresentation()?
Your mistake is thinking that the JPEG representation of an image is a UTF-8-encoded string. It's not. It's arbitrary binary data. UTF-8 strings aren't arbitrary sequences of bytes; there are rules about what bytes can follow other bytes.
You want to encode your JPEG data as a string suitable for use in an HTTP form submission. One way is to use base64 encoding, like this:
[body appendString:@"Content-Type: image/*\r\n"];
[body appendString:@"Content-Transfer-Encoding: base64\r\n\r\n"];
[body appendString:[data base64EncodedStringWithOptions: NSDataBase64Encoding76CharacterLineLength]];
On the other hand, you could use the binary
encoding and include the raw JPEG data directly. In that case, you would need to change the type of body
to NSMutableData
and build it up with different methods, as you cannot append arbitrary binary data to an NSMutableString
.
UPDATE
In Swift, with an NSMutableString
:
let data = UIImageJPEGRepresentation(image, 0.5)!
let body = NSMutableString()
body.append("Content-Type: image/*\r\n")
body.append("Content-Transfer-Encoding: base64\r\n\r\n")
body.append(data.base64EncodedString(options: .lineLength76Characters))
In Swift, with a String
:
let data = UIImageJPEGRepresentation(image, 0.5)!
var body = ""
body += "Content-Type: image/*\r\n"
body += "Content-Transfer-Encoding: base64\r\n\r\n"
body += data.base64EncodedString(options: .lineLength76Characters)
Get lower quality UIImage from NSData?
Although you may be able to build something like this using JPEG 2000 (you'd need to build your own copy of the jpeg library as discussed here, and then hand-write the reading code), I don't think you're going to get good return on investment there. The cost of reading the data off disk is still likely to overwhelm everything else.
First, if you're reading from your bundle, use PNG if at all possible. iOS highly optimizes PNGs stored in the bundle (part of the copying process is to rewrite them in an iOS-specific optimized format).
No matter what you do, if you want a place holder you are probably going to need to provide it somehow yourself, either as a separate file, or as a custom file format that you read and manage yourself. This wouldn't be an incredibly difficult format to devise, but you'd still need to do all the resizing beforehand somewhere.
The main key is that reading a large image file is expensive and you shouldn't do it on the main thread. You need to do this stuff on a background queue (GCD or operation) and update the UI when the data becomes available. There's no really easy way around this fact.
How to cast NSData to Data
You have a few issues.
- Why use
NSData
at all? Just useData
. - Your error is the fact that
imageData
doesn't actually represent a valid image soNSImage
isnil
but you try to force unwrap it.
Try something like this:
let imageData = Data(bytes: pixels)
Swift.print(imageData)
if let newImage = NSImage(data: imageData) {
// Do something with the image
} else {
// oops - can't create the image
}
Convert UTF-8 encoded NSData to NSString
If the data is not null-terminated, you should use -initWithData:encoding:
NSString* newStr = [[NSString alloc] initWithData:theData encoding:NSUTF8StringEncoding];
If the data is null-terminated, you should instead use -stringWithUTF8String:
to avoid the extra \0
at the end.
NSString* newStr = [NSString stringWithUTF8String:[theData bytes]];
(Note that if the input is not properly UTF-8-encoded, you will get nil
.)
Swift variant:
let newStr = String(data: data, encoding: .utf8)
// note that `newStr` is a `String?`, not a `String`.
If the data is null-terminated, you could go though the safe way which is remove the that null character, or the unsafe way similar to the Objective-C version above.
// safe way, provided data is \0-terminated
let newStr1 = String(data: data.subdata(in: 0 ..< data.count - 1), encoding: .utf8)
// unsafe way, provided data is \0-terminated
let newStr2 = data.withUnsafeBytes(String.init(utf8String:))
How to convert base64 into NSDATA in swift
This works:
Swift 3 and 4:
var audioData = Data(base64Encoded: recording_base64, options: .ignoreUnknownCharacters)
Swift 2:
var audioData = NSData(base64EncodedString: recording_base64, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)
Is there any way to know which Class instance , NSData Object contains?
Well....
it might be possible that your server is sending an image but its encoded.
getting your UIImage *img = null doesn't necessarily mean that the response data is not an Image. if you aren't decoding it back, it will be null of course
I think your response data is encoded in Base64...(most servers do)
if so,...
first download .h and .m files from this Link
add and import them in your project.
then use this code
NSString *str = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSData *data = [NSData dataFromBase64String:str];
UIImage *img = [[UIImage alloc] initWithData:data];
this img will have your image. if your server is really sending an image.
please note that.. not all of NSString *str in this code is representation of a UIImage
it might be some part of it. and the rest can be information related to this image.
so you have to decode only the image part of the response.
hope this helps....
NSData becomes nil after appending image data
A PNG representation is not valid UTF-8. postbody
contains 'arbitrary' data -- it cannot (reliably) be converted to a UTF-8 string (which is a structured, variable octet per character representation). So when you attempt to create a NSString from the data, it fails because the it finds the UTF-8 is malformed.
NSString *bodyString =
[[NSString alloc] initWithData:postbody encoding:NSUTF8StringEncoding];
^^^^^^^^ ^^^^
NSUTF8StringEncoding gives me this %0A%20%20%20%20%22http://example.com/example.jpg%22%0A
The log output you show appears to be an array, since it has parentheses with the string on a separate line.
You shouldn't need to encode the string if it's already a valid URL string and in fact doing so is wrong and will break things.
Related Topics
How to Compare Two Strings to Check If They Have Same Characters Swift 4
iOS 8 Swift Audio Playback Execute Method on Completion
Swift: How to Get Information for an Application Which Is Not Running
How to Call a Func Within a Closure
Store Data in Custom Class Array in Core Data
Filtering Dictionary in Swift 4 Fails in Xcode, But Succeeds in Playground
Replace Multiple Words from a String Based on the Values in an Array
Is There a Neat Way to Represent a Fraction as an Attributed String
Realm Error Domain=Io.Realm.Unknown Code=89 "Operation Canceled"
Swift Uikit Dynamics Add Collision Boundary. After Rotation Does Not Work Correctly
Where to Implement Nsvaluetransformer for Core Data in Swift
Url Constructor Doesn't Work with Some Characters
How to Get Video Duration Fro Avasset in Swift
Swift - Creating Shadow with 2 Different Colours for Imageview
Binary Operator '==' Cannot Be Applied to Operands of Type 'Uilabel' and 'String'