I have an iPhone application that needs to save an image onto the database in BLOB format. The problem is that if the image is in .gif format then it cannot be converted to NSDATA format and hence i am not been able to save that onto the database in BLOB format.
What should I do?
Please help with some code..
Thanks in advance
Joy
A gif image can be converted into NSData...Here's the code snippet:
NSString *pathForGif = [[NSBundle mainBundle] pathForResource: #"gifFile" ofType: #"gif"];
NSData *gifData = [NSData dataWithContentsOfFile: pathForGif];
NSLog(#"Data: %#", gifData);
The log looked something like this:
Data: <47494638 39616400 6400f7ff 001f3546 a71a2568 7a85bacd caa8a99a a8ada689 969599a8
a7684430 282e3496 9b97b5bd b69aa69b 47596667 7679dbe9 eb076997 efd9ce0f 2532c9d6 cc908875
d7dddb86 8c89c9c7 bac8cdc9 c9764fc9 bcadd38f 69c8141e 6b554eb0 8e72a99a 8c566a74 e8ecedef
e8d48b77 6c733526 56636871 6555eed6 b8cdb294 ... 76797acc d9d76667 66ba6743 f2a30f88 948b5657
58999688 a95737fa d05edad9 cbd08658 aebbca37 55660516 248d6c55 acb7b847 5356dae8 dca95944
d8dceb4a 322c4646 45344956 353f4677 847aaa64 449a5436 020d13d7 ccb96c2c 17b7ab9a 8c9ba196>
Related
I've been looking into source code of Research Kit Example called ORKTest:
if (type.integerValue == ORKConsentSectionTypeDataGathering) {
/*
Tests PDF content instead of text, HTML for Learn More.
*/
NSString *path = [[NSBundle mainBundle] pathForResource:#"SAMPLE_PDF_TEST" ofType:#"pdf"];
consentSection.contentURL = [NSURL URLWithString:path];
}
It used a local PDF file path in .contentURL,and I'd like to replace it with a online PDF url such as http://examle.com/file/example.pdf
consentSection.contentURL = NSURL.fileURLWithPath("http://example.com/file/example.pdf")
or
consentSection.contentURL = NSURL.fileURLWithPath("example.com/file/example.pdf")
but only got an empty page(the url that I used worked fine on browser,just a pdf file).
Anyone got any ideas,please?
NSURL.fileURLWithPath only works with local files. You have to put it in app's sandbox, then ask consentSection to load it.
I need to make a conversion from a DICOM image to a JPG/PNG and save the image using VTK, but the image that I produce does not match the original.
I know I need rescaling the pixels of the image to convert it but I do not know how. Does anyone know how I can do the conversion properly?
Below, my code in python:
from vtk import *
reader = vtkDICOMImageReader()
reader.SetFileName('image.dcm')
reader.Update()
castFilter = vtkImageCast()
castFilter.SetOutputScalarTypeToUnsignedChar()
castFilter.SetInputConnection(reader.GetOutputPort())
castFilter.Update()
writer = vtkJPEGWriter()
writer.SetFileName('output.jpg')
writer.SetInputConnection(castFilter.GetOutputPort())
writer.Write()
DICOMs in MRI and CT modalities are generally short types, and you are casting the image to unsigned char mercilessly.
If you are trying to get a corresponding uchar image, you should be using vtkImageShiftScale, just like the vtkImageCast docs say:
Warning
As vtkImageCast only casts values without rescaling them, its use is not recommented. vtkImageShiftScale is the recommented way to
change the type of an image data.
I made the conversion, here is my code:
from vtk import vtkDICOMImageReader
from vtk import vtkImageShiftScale
from vtk import vtkPNGWriter
reader = vtkDICOMImageReader()
reader.SetFileName('image.dcm')
reader.Update()
image = reader.GetOutput()
shiftScaleFilter = vtkImageShiftScale()
shiftScaleFilter.SetOutputScalarTypeToUnsignedChar()
shiftScaleFilter.SetInputConnection(reader.GetOutputPort())
shiftScaleFilter.SetShift(-1.0*image.GetScalarRange()[0])
oldRange = image.GetScalarRange()[1] - image.GetScalarRange()[0]
newRange = 255
shiftScaleFilter.SetScale(newRange/oldRange)
shiftScaleFilter.Update()
writer = vtkPNGWriter()
writer.SetFileName('output.jpg')
writer.SetInputConnection(shiftScaleFilter.GetOutputPort())
writer.Write()
I am trying to cache an image retrieved from Flickr. In order to create a unique filename for the cached image, I use CFURLCreateStringByAddingPercentEscapes to percent escape the URL. Appending that to the cache directory, I get a URL with the embedded Flickr URL properly percent escaped; but when I try to cache the image using NSData writeToURL:options:error: I get "The operation couldn’t be completed. No such file or directory" - and it shows the file URL with the original, unescaped Flickr URL where the file name should be.
For example, I NSLog the URL as:
file://localhost/Users/rick/Library/Application%20Support/iPhone%20Simulator/6.1/Applications/77C4A7AA-C386-4575-AD21-B4027D080408/Library/Caches/http%3A%2F%2Ffarm3.static.flickr.com%2F2887%2F9391679341_26643bcafa_b.jpg
but the error message shows
NSFilePath=/Users/rick/Library/Application Support/iPhone Simulator/6.1/Applications/77C4A7AA-C386-4575-AD21-B4027D080408/Library/Caches/http://farm3.static.flickr.com/2887/9391679341_26643bcafa_b.jpg
It's as if in the process of converting the URL to a file path, writeToURL is removing the percent escapes.
Is there a way to prevent this from happening, or do I just need to come up with another way to generate unique names based on the url?
Here's the relevant code:
NSURL *cacheDirectoryURL=[[fileManager URLsForDirectory:NSCachesDirectory inDomains:NSUserDomainMask] lastObject];
NSString *photoURLString= (NSString *) CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL,
(__bridge CFStringRef)([self.photoURL absoluteString]),
NULL,
(CFStringRef) #"!*'();:#&=+$,/?%#[]",
kCFStringEncodingUTF8));
if (photoURLString)
{
NSURL *cachedPhotoURL=[NSURL URLWithString:[[cacheDirectoryURL absoluteString] stringByAppendingString:photoURLString]];
NSData *photoData=[NSData dataWithContentsOfURL:cachedPhotoURL];
if (photoData)
{
UIImage *image=[UIImage imageWithData:photoData];
self.imageView.image=image;
[self setupScrollView]; // new image, need to adjust scroll view
} else {
dispatch_queue_t fetchQueue=dispatch_queue_create("photo downloader", NULL);
dispatch_async(fetchQueue, ^{
NSData *photoData=[NSData dataWithContentsOfURL:self.photoURL];
NSError *error;
if ([photoData writeToURL:cachedPhotoURL options:NSDataWritingAtomic error:&error])
{
NSLog(#"Cached photo");
} else {
NSLog(#"Failed to cache photo");
NSLog(#"%#",error);
}
});
}
}
Thanks in advance for your help!
The problem is that [NSURL URLWithString:...] parses the given string and interprets the
percent escapes. Generally, to create a URL for a file system path, fileURLWithPath:
should be used.
In your case, the following simple code should work:
NSURL *cachedPhotoURL = [cacheDirectoryURL URLByAppendingPathComponent:photoURLString]
I am creating an object classifier using OpenCV and to avoid having to train the classifiers every time the app is launched I would like to somehow store them in a file. The most convenient way available seems to be using OpenCVs FileStorage class.
I gave this a shot but it didn't seem to work. The saved file did not show up anywhere though I did not receive an error. I suppose iOS doesn't just let you save any file. An alternative way would be to retrieve the YAML as a string, convert it to an NSString and save it in a property list, but I am not sure how this can be done or whether it is even possible.
Any help would be greatly appreciated.
I managed to get the FileStorage class working with iOS. The problem was that I needed to make sure the file was being created in iOSs designated Documents Directory. Here is some sample code:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docs = [paths objectAtIndex:0];
NSString *vocabPath = [docs stringByAppendingPathComponent:#"vocabulary.xml"];
FileStorage fs([vocabPath UTF8String], FileStorage::WRITE);
// vocab is a CvMat object representing the vocabulary in my bag of features model
fs << "vocabulary" << vocab;
fs.release();
// READING
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docs = [paths objectAtIndex:0];
NSString *vocabPath = [docs stringByAppendingPathComponent:#"vocabulary.xml"];
FileStorage fs([vocabPath UTF8String], FileStorage::READ);
// vocab is a CvMat object representing the vocabulary in my bag of features model
fs["vocabulary"] >> vocab;
fs.release();
I want to display large photos in my Facebook app's feed view immediately. Is it possible to get the large photo src URL from a stream/feed using one API call? The photo id is returned in the stream/feed and one can of course then supply this photo id in an additional FQL or graph API call to retrieve all the information about that photo. However, is there a way using multi-query or batch calls to get a larger photo src url using one API roundtrip?
I haven't tried this with stream/feed photos, but the generally accepted way of doing this is:
http://graph.facebook.com/{ID of object}/picture
If you want the "large" version, you would do:
http://graph.facebook.com/{ID of object}/picture?type=large
I'm not 100% sure if this would work for an actual photo (instead of a user profile picture or page profile pic), but I have a hunch it will - the only caveat is that you obviously must have a logged in user that is authorized to view the photo (unless it's public).
If anybody is looking to this and type large is not enough, I found other solutions.
Type large is kind of small anyway (close to 200px). You can get larger image by adding i.e. ?width=1000 or ?height=1000. Facebook will return picture closest to given dimension and preserve aspect ratio. When passing both dimenstions like ?width=1000&height=1000, facebook will cut image to given dimensions (in this case square).
Use Facebook UserId (Oject ID) to get the picture.
https://graph.facebook.com/173xxxx8635/picture?type=large&redirect=false
which returns JSON data with picture URL.
{
"data": {
"is_silhouette": false,
"url": "https://fbcdn-profile-a.akamaihd.net/xxx/xyz/1cc066a2cae3f301d"
}
}
A good trick with the new api is to get the pic_cover field from the event table and to process it according to the size you want to use
I found when I was having this trouble that it turned out to be the picture I was downloading rather than the size I was setting it.
If for example I downloaded all my photos with a request of
[FBRequestConnection startWithGraphPath:#"/me/photos?fields=created_time,name,picture&type=tagged" parameters:nil HTTPMethod:#"GET" completionHandler:^(FBRequestConnection * connection, id result, NSError *error) {
NSDictionary * userData = (NSDictionary *)result;
NSMutableArray * array = [[NSMutableArray alloc] initWithArray:userData[#"data"]];
for (NSDictionary * dict in eventsToAdd) {
UIImage * image = dict[#"picture"]
}
}];
I am using the dictionary key search "picture" as I want the picture.
This though will get me a lower quality picture than if I searched for "source" in this search:
[FBRequestConnection startWithGraphPath:#"/me/photos?fields=created_time,name,source&type=tagged" parameters:nil HTTPMethod:#"GET" completionHandler:^(FBRequestConnection * connection, id result, NSError *error) {
NSDictionary * userData = (NSDictionary *)result;
NSMutableArray * array = [[NSMutableArray alloc] initWithArray:userData[#"data"]];
for (NSDictionary * dict in eventsToAdd) {
UIImage * image = dict[#"source"]
}
}];
If you go on the Facebook API explorer and search for photos and then click on the picture and source jpg links you can see the difference in size and quality.
Since changing this method I have managed to get rid of using the type parameters as it doesn't seem to make a different.
Note: I am using iPhone and not iPad or a larger screen so I don't know how this affects bigger screens.
The answer by #streetlogics works fine but only on pictures that have {object_id}.
http://graph.facebook.com/{object_id}/picture
But I also wanted large pictures for the feed's shared links, which sometimes don't have {object_id}. I finally realized that the {picture} thumbnail URL contains the encoded URL for the original site's large image:
https://external.xx.fbcdn.net/safe_image.php?d=AQBe9UvGd0vPbAHP&w=130&h=130&url=http%3A%2F%2Fskift.com%2Fwp-content%2Fuploads%2F2015%2F12%2Fpollution.jpg&cfs=1
--> contains -->
http://skift.com/wp-content/uploads/2015/12/pollution.jpg
So I made a loop that checks for {object_id} and if not present then extracts the URL from {picture}:
if(isset($post['object_id'])) {
echo "http://graph.facebook.com/".$post['object_id']."/picture";
}
elseif(isset($post['picture'])) {
echo urldecode(preg_replace('/&cfs.*/', '', preg_replace('/.*url=/', '', $post['picture'])));
}
else {
echo "no_large_image";
}