How can I add images from a folder to my swift code? - arrays

I am trying to create an animated image background for my swift application. I added a group of 300 JPG images to my assets folder, and am wondering how I can access that folder in my code, iterate through it, and append it to an UIImage array? Or if there is an easier way to do this let me know.

You can name the images accordingly to the frame order
e.g.
image0, image1, image2 ... imageN
and then iterate
var imagesArray:[UIImage] = []
for i in 0...100 {
guard let image = UIImage(named: "image\(i).png") else {
fatalError("Couldn't find image\(i).png")
}
imagesArray.append(image)
}
imageView.animationImages = imagesArray

You can use animatedImageNamed:duration:
Let's say you are animating a spinner. Copy all of your frames into the project and name them as follows:
spinner-1.png
spinner-2.png
spinner-3.png
etc.
Then create the image via:
[UIImage animatedImageNamed:#"spinner-" duration:1.0f];
According to Apple document,
This method loads a series of files by appending a series of numbers to the base file name provided in the name parameter. For example, if the name parameter had ‘image’ as its contents, this method would attempt to load images from files with the names ‘image0’, ‘image1’ and so on all the way up to ‘image1024’. All images included in the animated image should share the same size and scale.
and you can use third party library like FLAnimatedImage or uiimage-from-animated-gif
Hope this will help :)

Related

How do I get an array of file names from the iOS File Manager

I'm creating an Audio Recording app and have declared an empty array to store all the names of the files.
var recordingTitles: [String] = []
When I launch the app, I have a function that checks what files are already stored in the File Manager and returns the number of files in order to display the correct number of cells in the collectionView.
override func viewDidLoad() {
super.viewDidLoad()
getNumberOfRecordings()
}
// Get number of actual recording files stored in the File Manager Directory
func getNumberOfRecordings() {
let directoryUrl = getDirectory()
do {
contentsOfFileManager = try myFileManager.contentsOfDirectory(at: directoryUrl, includingPropertiesForKeys: [URLResourceKey(rawValue: recordingsKey)], options: .skipsHiddenFiles)
} catch let error {
print(error.localizedDescription)
}
numberOfRecordings = contentsOfFileManager.count
}
I would like to obtain the names of the files and assign them to the "recordingTitles" array in order to display the correct title for each cell. I've tried reading over the Apple docs for File Manager but haven't found a solution yet. Thank you in advance for your help!
So, contentsOfFileManager is going to consist of NSURL objects. These objects have different fields you can pluck out and use. It looks like you're interested in just the filename so I'd like to draw your attention to the lastPathComponent field of NSURL. From the docs:
This property contains the last path component, unescaped using the replacingPercentEscapes(using:) method. For example, in the URL file:///path/to/file, the last path component is file.
In other words, calling myNsurl.lastPathComponent should yield you the filename. So you can loop through the array that's returned by myFileManager.contentsOfDirectory and get the lastPathComponent of each one and add them to another array which will contain just the filenames.
Use the map function. You probably want something like this:
recordingTitles = try myFileManager.contentsOfDirectory(at:directoryURL,
includingPropertiesForKeys: nil).map {$0.lastPathComponent}

How to visualize LabelMe database using Matlab

The LabelMe database can be downloaded from http://www.cs.toronto.edu/~norouzi/research/mlh/data/LabelMe_gist.mat
However, there is another link http://labelme.csail.mit.edu/Release3.0/
The webpage has a toolbox but I could not find any database to download. So, I was wondering if I could use the LabelMe_gist.mat which has the following fields. The field names contins the labels for the images, and img perhaps contains the images. How do I display the training and test images? I tried
im = imread(img)
Error using imread>parse_inputs (line 486)
The filename or url argument must be a string.
Error in imread (line 336)
[filename, fmt_s, extraArgs, msg] = parse_inputs(varargin{:});
but surely this is not the way. Please help
load LabelMe_gist.mat;
load('LabelMe_gist.mat', 'img')
Since we had no idea from your post what kind of data this is I went ahead and downloaded it. Turns out, img is a collection of 22019 images that are of size 32x32 (RGB). This is why img is a 32 x 32 x 3 x 22019 variable. Therefore, the i-th image is accessible via imshow(img(:,:,:,i));
Here is an animation of all of them (press Ctrl+C to interrupt):
for iImage = 1:size(img,4)
figure(1);clf;
imshow(img(:,:,:,iImage));
drawnow;
end

image array creating unwanted image in top corner

I have this set up in my main.lua file
images = {
display.newImageRect("images/player3.png", 45,35),
display.newImageRect("images/player4.png", 45,35),
display.newImageRect("images/player5.png", 45,35)
}
and call it from my game.lua file with this code:
bird = images[math.random(1,3)]
bird.x, bird.y = -80, 140
bird.name = "bird"
physics.addBody( bird, "static")
bird.isFixedRotation = true
birdIntro = transition.to(bird,{time=1000, x=100, onComplete= birdReady})
A random image spawns (where it should, in the middle) but the issue is that a second image spawns and sits in the top left corner of the screen (slightly off screen). I can't seem to remove it and keep the one correct image only, any solutions?
Your help is greatly appreciated.
Thanks
I think the problem is your images array. I've found by calling the display.newImageRect it will create the object and plop it on the screen. Even if you don't want it to show the object right then. Usually I see this when I should be putting it in a display group (not sure if you are doing that).
I think the solution might be to have the array of images be the image paths and then you can set bird equal to a new image rect at that point, thus only creating 1 image rectangle instead of 3.
images = {
"images/player3.png",
"images/player4.png",
"images/player5.png",
}
bird = display.newImageRect(images[math.random(1,3)],45,35)
Let me know if that works.

LoaderMax: setting array as a container (ImageLoader)

So, I have a LoaderMax instance loading images from various URLs. I want to add all loaded images to an array.
Here's my code:
var photosArray:Array = new Array(5);
var imageLoadingQueue:LoaderMax = new LoaderMax({name:"mainQueue", onComplete:completeHandler});
for (var g:uint=0; g<5; g++)
{
imageLoadingQueue.append(new ImageLoader("/img" + g + ".jpg", {name:"photo", container:photosArray[g], noCache:false, smoothing:true, width:126, height:126, scaleMode:"proportionalOutside"}));
}
imageLoadingQueue.load();
private function completeHandler(e:LoaderEvent):void
{
trace("finished loading pictures!");
//the next two lines will return an error (saying that photosArray[1] is null)
stage.addChild(photosArray[1]);
photosArray[1].x = 250;
}
A few problems:
If I set the container of the image being loaded to the Array, it won't work. I'm not being able to access the image inside the array because it says it's null.
If I set the container of the image being loaded to "this" (using the container property when appending a new ImageLoader) and, on the completeHandler, set my array equal to event.target.content, it kinda works (but it's not the ideal). The problem is that, by doing so, the images are appearing on the stage as they are loaded, and I do no want them to do so.
Any help would be heavily appreciated.
Thanks!!
David is correct, but I also wanted to mention that the LoaderMax's "content" is actually an array of all of its children's content, so you could just use that for simplicity. Keep in mind that ImageLoaders automatically create a Sprite (technically called a "ContentDisplay") to drop the image into so you probably don't need to create ANOTHER Sprite (a container for the container).
var photos:Array = imageLoadingQueue.content;
stage.addChild(photos[1]);
The other nice thing is that it creates the ContentDisplay Sprites immediately, even before any content is loaded into them, so you can place them and size them however you want while (or before or after) loading occurs.
The container needs to be a DisplayObjectContainer. ImageLoader will try to add the image to the container using addChild(), so obviously this won't work with an empty array. Create a new Sprite for each image and add it into the array first:
for (var g:uint=0; g<5; g++)
{
photosArray[g] = new Sprite();
imageLoadingQueue.append(new ImageLoader("/img" + g + ".jpg", {name:"photo", container:photosArray[g], noCache:false, smoothing:true, width:126, height:126, scaleMode:"proportionalOutside"}));
}

Byte Array copy in Jsp

I am trying to append 2 images (as byte[] ) in GoogleAppEngine Java and then ask HttpResponseServlet to display it.
However, it does not seem like the second image is being appended.
Is there anything wrong with the snippet below?
...
resp.setContentType("image/jpeg");
byte[] allimages = new byte[1000000]; //1000kB in size
int destPos = 0;
for(Blob savedChart : savedCharts) {
byte[] imageData = savedChart.getBytes(); //imageData is 150k in size
System.arraycopy(imageData, 0, allimages, destPos, imageData.length);
destPos += imageData.length;
}
resp.getOutputStream().write(allimages);
return;
Regards
I would expect the browser/client to issue 2 separate requests for these images, and the servlet would supply each in turn.
You can't just concatenate images together (like most other data structures). What about headers etc.? At the moment you're providing 2 jpegs butted aainst one another and a browser won't handle that at all.
If you really require 2 images together, you're going to need some image processing library to do this for you (or perhaps, as noted, AWT). Check out the ImageIO library.
Seem that you have completely wrong concept about image file format and how they works in HTML.
In short, the arrays are copied very well without problem. But it is not the way how image works.
You will need to do AWT to combine images in Java

Resources