Now: i am uploading data and saving it to my public folder:
let info = req.data
guard let fileBytes = info["photo"]?.bytes
else {
var answerJson = JSON();
try answerJson.set("success", "false");
return answerJson
}
let dir = URL(fileURLWithPath: self.config.workDir).appendingPathComponent("Public/FleaMarketProductImages")
let dirWithImage = dir.appendingPathComponent("test3.jpg")
let fileManager = FileManager()
let data = Data(bytes: fileBytes)
fileManager.createFile(atPath: dirWithImage.path, contents: data, attributes: nil)
Then on device for downloaing this file i am doing next:
Alamofire.download(url).responseData { response in
if let data = response.result.value {
completionHandler(data)
}
}
I am getting some data, but when i do UIImage(data: data), i dont see my image. Where i did something wrong? Maybe there is another way to do it. And files in my public directory dont looks like image. They just files. Maybe do you know how to save it like an image????
The uploaded image will be one part of a multi-part request, so you need to use just the part that contains the image. .bytes will give you the whole request. I use:
guard let fileBytes = info.formData?["photo"]?.part.body
Or
guard let fileBytes = info?["photo"]?.part.body
if you aren't using a form.
Related
I know there are many solutions around related to converting an Image string into data and to set the image in an ImageView. But unfortunately, nothing worked in my case. I have a parsed JSON field which returns an Image as a string. So I'm trying to convert that String as URL and then to get URL data to display the image. But when the error is throwing when I try to get the data from URL like
let testImage = Data(contentsOf: forecastURL! as URL)
Error: "Incorrect argument label in call (have 'contentsOf:', expected
'dictionary:')"
if let url21 = URL(string: brandingLogo) {
do {
let testImage = Data(contentsOf: url21)
self.BrandingBarImage.image = UIImage(data: testImage)
}
catch
{
print("error")
}
}
**Code for brandingLogo:**
guard let url = URL(string: urlJson) else {return}
let task = URLSession.shared.dataTask(with: url) { (data1, response, error) in
do {
let parsedData = try JSONSerialization.jsonObject(with:data1!) as? [String:Any]
let statusList = parsedData?["data"] as? [String:Any]
let anotherData = statusList?["data"] as? [String:Any]
if let players = anotherData?["players"] as? [[String:Any]] {
for logo in players {
self.brandingLogo = logo["logo_app_branding_bar"] as? String
print(self.brandingLogo)
}
brandingLogo is parsed from Json and its value is: https://media.socastsrm.com/wordpress/wp-content/blogs.dir/223/files/2018/01/blank-300x95.png
so, I'm assuming that when this 'brandingLogo' is considered as String, it takes only the actual string like :
https://media.socastsrm.com/wordpress/wp-content/blogs.dir/223/files/2018/01/blank-300x95.png
And so I'm trying to convert that image string to URL and then to get Data
Any help is appreciated. Thank you
I am trying to save images in a directory. Images are correctly saved in the right place, but when I inspect these with the path in the finder, all the images are damaged and unsable.
damaged images
Below the static method:
static func writeImageFile(with data: Data, issue: Issue, page: Int, isThumbnail: Bool) throws -> URL {
let url = MediaFileManager.issueImagesDirectoryURL(issue: issue).ensuringDirectoryExists()
let imageURL = url.appendingPathComponent(imageName(for: page, isThumbnail: isThumbnail))
try data.write(to: imageURL)
return url
}
And the call in the class:
DispatchQueue.main.async {
guard let data = result.data else {
self.downloadDidFail(for: result.page)
return
}
do {
let writeImageFile = try MediaFileManager.writeImageFile(with: data, issue: self.issue, page: result.page, isThumbnail: false)
let writeThumbFile = try MediaFileManager.writeImageFile(with: data, issue: self.issue, page: result.page, isThumbnail: true)
print(writeImageFile)
print(writeThumbFile)
} catch let error as NSError {
print(error.localizedDescription)
}
}
I will assume, since you don't quite specify this, that you have a bunch of UIImage objects.
And I also noticed that you want your images to be saved as JPEG, which is no trouble at all, don't worry.
I would go with something like this:
if let image = UIImage(named: "example.png") {
if let data = UIImageJPEGRepresentation(image, 1.0) {
let filename = getDocumentsDirectory().appendingPathComponent("copy.png")
try? data.write(to: filename)
}
}
Where the func getDocumentsDirectory() is the following:
func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return paths[0]
}
You might wonder why I used 1.0 for the second parameter in UIImageJPEGRepresentation, well that's the JPEG quality mapped between 0.0 and 1.0 (it's a float).
If you have any details that I am not aware of, please reply and I will try to help accordingly.
Hope it helps you, cheers!
Source: link
Have you tried to load the image to a UIImageView to see if the images are being properly downloaded? imageView.image = UIImage(data: data).
But I also detect that you're saving Data instead of the image, in order to make sure that you're saving an image I would try the following
static func writeImageFile(with data: Data, issue: Issue, page: Int, isThumbnail: Bool) throws -> URL {
let url = MediaFileManager.issueImagesDirectoryURL(issue: issue).ensuringDirectoryExists()
let imageURL = url.appendingPathComponent(imageName(for: page, isThumbnail: isThumbnail))
let image = UIImage(data: data)
let imgData = UIImageJPEGRepresentation(image, 1)
try imgData.write(to: imageURL)
return url
}
Yes, it might have unnecessary steps, worth trying, this way we're making sure that it's saved as Jpeg. But again, I would check if the images are being properly downloaded first.
I have base64 image string which is downloaded from a webpage using POST request and I am trying to decode and display inside imageview but it's not working. I have tried couple of sources but no luck :(
let base64String = "data:image/jpg;base64,/9j/4aaQSkZJRg0BMADAE15a5df.....H/12Q=="
Currently, trying this method:
if let decodedData = Data(base64Encoded: base64String, options: .ignoreUnknownCharacter) {
let image = UIImage(data: decodedData)
ImageView.image = image
} else {
print("error in decoding")
}
Tried NSData method also:
let dataDecode:NSData = NSData(base64Encoded: base64String!, options:.ignoreUnknownCharacters)!
let image= UIImage(data: dataDecode as Data)!
yourImageView.image = image
The else part always executes. I have tried this in xCode playground by putting encoded string in static variable and noticed nil in front of if condition line.
Not sure, what I am doing wrong?
Your base64String is actually a URL with a data scheme. There is built in support for these types of URLs.
You can do something like:
let dataString = "data:image/jpg;base64,/9j/4aaQSkZJRg0BMADAE15a5df.....H/12Q=="
let dataURL = URL(string: dataString)
let data = Data(contentsOf: dataURL)
let image = UIImage(data: data)
I leave it as an exercise to properly handle optional values and error handling.
be careful, only part of the string represents the image
let base64String = "data:image/jpg;base64,9j/4aaQSkZJRg0BMADAE15a5df.....H/12Q=="
I have to upload document in swift , I have to do this using the iCloud , so that I can upload file to my server using icloud
Swift 3.x
let filePath = ... //URL of the PDF
let fileData = try Data.init(contentsOf: filePath!)
let fileStream:String = fileData.base64EncodedString(options: NSData.Base64EncodingOptions.init(rawValue: 0))
Drag the pdf file to the project or five the path before to hold
let url1 = Bundle.main.url(forResource: "pdffilename without extension", withExtension: "pdf")
let one1 = NSData(contentsOf: url1!)
let pdfstring:String = one1!.base64EncodedString(options: .endLineWithLineFeed)
print(pdfstring)
let filePath = "" // real path of the pdf file
let fileData = NSData(contentsOfFile: path)
let fileStream = data.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength) // base64 string
Where would you pick the file, That file path has to be given:
First generate the base64 string you can use it
Then generate the bytes
Which one comfortable could use it.
do {
let fileData = try Data.init(contentsOf: filePath!)
let fileStream:String = fileData.base64EncodedString(options: NSData.Base64EncodingOptions.init(rawValue: 0))
let decodeData = Data(base64Encoded: fileStream, options: .ignoreUnknownCharacters)
body.append(decodeData!)
}
catch { }
I am trying to create an iOS Photo Extension which compresses images, and this is finishContentEditingWithCompletionHandler function:
func finishContentEditingWithCompletionHandler(completionHandler: ((PHContentEditingOutput!) -> Void)!) {
dispatch_async(dispatch_get_global_queue(CLong(DISPATCH_QUEUE_PRIORITY_DEFAULT), 0)) {
atomically: true)
let url = self.input?.fullSizeImageURL
if let imageUrl = url {
var fullImage = UIImage(contentsOfFile:
imageUrl.path!)
//Just compresses the image
let renderedJPEGData =
UIImageJPEGRepresentation(fullImage, self.comprestionRatioFloat)
var currentFilter = "FakeFilter"
renderedJPEGData.writeToURL(
output.renderedContentURL,
atomically: true)
let archivedData =
NSKeyedArchiver.archivedDataWithRootObject(
currentFilter)
output.adjustmentData = PHAdjustmentData(formatIdentifier:"MyApp.Ext", formatVersion:"1.0", data:archivedData)
}
completionHandler?(output)
// Clean up temporary files, etc.
}
}
When I test it on the device it says "Unable to Save Changes", Is there anything wrong?
Finally I've found out it's because the output image is almost the same as input. A little scaling down the output image fixed the problem.