image array creating unwanted image in top corner - arrays

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.

Related

Codename One rounded image from an internet source

I am trying to display a rounded image that I get straight from the Internet.
I used the code below to create a round mask, get the image from the Internet, then tried to either set the mask on the image or the label itself. None of these approaches worked. If I remove the mask, the image is displayed fine. If I keep the code to set the mask then all I see is an empty white circle.
I have the idea that if I apply the mask on the image itself, then it may not take effect because the image was not downloaded at the time the mask was applied.
But I don't seem to understand why calling setMask on the label is also not working.
// Create MASK
Image maskImage = Image.createImage(w, l);
Graphics g = maskImage.getGraphics();
g.setAntiAliased(true);
g.setColor(0x000000);
g.fillRect(0, 0, w, l);
g.setColor(0xffffff);
g.fillArc(0, 0, w, l, 0, 360);
Object mask = maskImage.createMask();
// GET IMAGE
com.cloudinary.Cloudinary cloudinary = new com.cloudinary.Cloudinary(ObjectUtils.asMap(
"cloud_name", "REMOVED",
"api_key", "REMOVED",
"api_secret", "REMOVED"));
// Disable private CDN URLs as this doesn't seem to work with free accounts
cloudinary.config.privateCdn = false;
Image placeholder = Image.createImage(150, 150);
EncodedImage encImage = EncodedImage.createFromImage(placeholder, false);
Image img2 = cloudinary.url()
.type("fetch") // Says we are fetching an image
.format("jpg") // We want it to be a jpg
.transformation(
new Transformation()
.radius("max").width(150).height(150).crop("thumb").gravity("faces").image(encImage, "http://upload.wikimedia.org/wikipedia/commons/4/46/Jennifer_Lawrence_at_the_83rd_Academy_Awards.jpg");
Label label = new Label(img2);
label.setMask(mask); // also tried to do img2.applyMask(mask); before passing img2
So I tried various things:
1) Removing the mask that was set through cloudinary - That did not work
2) applied the mask to the placeholder & encoded image (as expected these shouldnt affect the final version that is getting published)
3) This is what works! I am not sure if the issue is really with downloading the picture before or after applying the mask.. time can tell down the road
Label label = new Label();
img2.applyMask(mask); // If you remove this line , the image will no longer be displayed, I will only see a rounded white circle ! I am not sure what this is doing, it might be simply stalling the process until the image is downloaded? or maybe somehow calling repaint or revalidate
label.setIcon( img2.applyMask(mask));
Here is what worked for me if anyone else is having similar issues:
//CREATE MASK
Image maskImage = Image.createImage(w, l);
Graphics g = maskImage.getGraphics();
g.setAntiAliased(true);
g.setColor(0x000000);
g.fillRect(0, 0, w, l);
g.setColor(0xffffff);
g.fillArc(0, 0, w, l, 0, 360);
Object mask = maskImage.createMask();
//CONNECT TO CLOUDINARY
com.cloudinary.Cloudinary cloudinary = new com.cloudinary.Cloudinary(ObjectUtils.asMap(
"cloud_name", "REMOVED",
"api_key", "REMOVED",
"api_secret", "REMOVED"));
// Disable private CDN URLs as this doesn't seem to work with free accounts
cloudinary.config.privateCdn = false;
//CREATE IMAGE PLACEHOLDERS
Image placeholder = Image.createImage(w, l);
EncodedImage encImage = EncodedImage.createFromImage(placeholder, false);
//DOWNLOAD IMAGE
Image img2 = cloudinary.url()
.type("fetch") // Says we are fetching an image
.format("jpg") // We want it to be a jpg
.transformation(
new Transformation()
.crop("thumb").gravity("faces")
.image(encImage, url);
// Add the image to a label and place it on the form.
//GetCircleImage(img2);
Label label = new Label();
img2.applyMask(mask); // If you remove this line , the image will no longer be displayed, I will only see a rounded white circle ! I am not sure what this is doing, it might be simply stalling the process until the image is downloaded? or maybe somehow calling repaint or revalidate
label.setIcon( img2.applyMask(mask));
Shai, I seriously appreciate your time!! Thank you very much. Will have to dig more into it if it gives me any other problems later but it seems to consistently work for now.
The Cloudinary API returns a URLImage which doesn't work well with the Label.setMask() method because, technically, a URLImage is an animated image (it is a placeholder image until it finishes loading, and then "animates" to become the target image).
I have just released a new version of the cloudinary cn1lib which gives you a couple of options for working around this.
I have added two new image() methods. One that takes an ImageAdapter parameter that you can use to apply the mask to the image itself, before setting it as the icon for the label. Then you wouldn't use Label.setMask() at all.
See javadocs for this method here
The other method uses the new Async image loading APIs underneath to load the image asynchronously. The image you receive in the callback is a "real" image so you can use it with a mask normally.
See javadocs for this method here
We are looking at adding a soft warning to the Label.setMask() and setIcon() methods if you try to add an "animated" image and mask it so that it is more clear.
I think the making code you set to the label might be conflicting with the masking code you get from Cloudinary.

storing images into to a cell in matlab

I understand that similar questions have been asked before but I have tried the other solutions and had no luck. Would really appreciate some help!
I want to 1.load a file of images, 2.read them with imread, 3.put that in a cell, 4.run my function stepwise on each array in the cell.
here is my function for 1 image/file
function sym_file(filename) %this calls for the image file name
j=im2double(rgb2gray(imread(filename)));
%reads the image, turns int into grayscale and double
if rem(size(j,2),2)~=0,j(:,1)=[];
if rem(size(j,1),2)~=0,j(1,:)=[];
end
end
%this made sure the rows and columns are even
jr=fliplr(j);
left=(j(:,1:size(j,2)/2));
right=(jr(:,1:size(j,2)/2));
t=sum(left,2);
u=sum(right,2);
symmetry= (left-right)./255;
symmetry2=reshape(symmetry,1,(numel(symmetry)));
imbalance=mean(symmetry2)
asymmetry=sqrt(mean(symmetry2.^2))
%runs calculations on image
figure('Name',num2str(filename),'NumberTitle','off')
subplot(3,2,1)
histogram(symmetry2,200)
title(['symmetry:' num2str(asymmetry)])
subplot(3,2,2)
imshow(j)
title(['imbalance:' num2str(imbalance)])
subplot(3,2,3)
imshow(left)
title('left')
subplot(3,2,4)
imshow(fliplr(right))
title('right')
impixelinfo;
subplot(3,2,5)
plot(1:length(t),t,'-r',1:length(u),u,'-b')
title('results,red=left/blue=right')
%printing results in a figure
So I would like to do this with a file of images rather than doing it file by file. What's the best way? Also, if someone knows how to store the data/figures in files that would be a bonus also.
Let me see if I got this straight: you have a set of images and you store them in a cell. You then want to apply a function to each image (in other words: to each element of the cell).
If so, just use cellfun()
Example:
X = imread('http://sipi.usc.edu/database/preview/aerials/3.2.25.png','png');
Y = imread('http://sipi.usc.edu/database/preview/misc/5.3.01.png','png');
my_cell{1} = X;
my_cell{2} = Y;
my_fftcell = cellfun(#fft2,my_cell,'UniformOutput', false)
In this case I loaded 2 images X and Y and stored them into my_cell (the brackets {} indicate to MATLAB/Octave that it is a cell). I then created another cell called my_fftcell which is the fft2 applied over each image.
To get many files from a folder/directory, you can just loop over each file in that directory and store it into the cell. Something like this:
Loading multiple images in MATLAB

Need to figure out how to use DeepZoomTools.dll to create DZI

I am not familiar with .NET coding.
However, I must create DZI sliced image assets on a shared server and am told that I can instantiate and use DeepZoomTools.dll.
Can someone show me a very simple DZI creation script that demonstrates the proper .NET coding technique? I can embellish as needed, I'm sure, but don't know where to start.
Assuming I have a jpg, how does a script simply slice it up and save it?
I can imagine it's only a few lines of code. The server is running IIS 7.5.
If anyone has a simple example, I'd be most appreciative.
Thanks
I don't know myself, but you might ask in the OpenSeadragon community:
https://github.com/openseadragon/openseadragon/issues
Someone there might know.
Does it have to be DeepZoomTools.dll? There are a number of other options for creating DZI files. Here are a few:
http://openseadragon.github.io/examples/creating-zooming-images/
Example of building a Seadragon Image from multiple images.
In this, the "clsCanvas" objects and collection can pretty much be ignored, it was an object internal to my code that was generating the images with GDI+, then putting them on disk. The code below just shows how to get a bunch of images from file and assemble them into a zoomable collection. Hope this helps someone :-).
CollectionCreator cc = new CollectionCreator();
// set default values that make sense for conversion options
cc.ServerFormat = ServerFormats.Default;
cc.TileFormat = ImageFormat.Jpg;
cc.TileSize = 256;
cc.ImageQuality = 0.92;
cc.TileOverlap = 0;
// the max level should always correspond to the log base 2 of the tilesize, unless otherwise specified
cc.MaxLevel = (int)Math.Log(cc.TileSize, 2);
List<Microsoft.DeepZoomTools.Image> aoImages = new List<Microsoft.DeepZoomTools.Image>();
double fLeftShift = 0;
foreach (clsCanvas oCanvas in aoCanvases)
{
//viewport width as a function of this canvas, so the width of this canvas is 1
double fThisImgWidth = oCanvas.MyImageWidth - 1; //the -1 creates a 1px overlap, hides the seam between images.
double fTotalViewportWidth = fTotalImageWidth / fThisImgWidth;
double fMyLeftEdgeInViewportUnits = -fLeftShift / fThisImgWidth; ; //please don't ask me why this is a negative numeber
double fMyTopInViewportUnits = -fTotalViewportWidth * 0.3;
fLeftShift += fThisImgWidth;
Microsoft.DeepZoomTools.Image oImg = new Microsoft.DeepZoomTools.Image(oCanvas.MyFileName.Replace("_Out_Tile",""));
oImg.ViewportWidth = fTotalViewportWidth;
oImg.ViewportOrigin = new System.Windows.Point(fMyLeftEdgeInViewportUnits, fMyTopInViewportUnits);
aoImages.Add(oImg);
}
// create a list of all the images to include in the collection
cc.Create(aoImages, sMasterOutFile);

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"}));
}

GAE images.resize with fixed proportional crop

I need to resize and crop to exactly 60x80px from various size and
aspect ratio. Just before i put into Datastore. Anyone already got
this issue resolved.
Currently i already succed to just transform it to exact height (80px)
with various width which nott look so good when i try to display it on
a list. e.g jcaroussel.
My db.put code is like bellow:
if users.get_current_user():
personal.personal_id = int(self.request.get('personal_id'))
personal.name = self.request.get('name')
personal.latitude = self.request.get('latitude')
personal.info = self.request.get('info')
photo = images.resize(self.request.get('img'), 0, 80)
personal.photo = db.Blob(photo)
personal.lc_id = int(self.request.get('lc_id'))
personal.put()
self.redirect('/admin/personal')
else:
self.response.out.write('I\'m sorry, you don\'t have permission to add this LP Personal Data.')
I just want to do similar result when we upload our avatar on google
talk/google chat.
Anyone solved this?
Thx
After your resize your image down to 80 pixels in height, you would have to use the crop function as defined here. For example:
img = images.Image(self.request.get('img'))
img.resize(0, 80)
resized_img = img.execute_transforms(output_encoding=images.JPEG)
left_x = (resized_img.width - 60) / 2
resized_img.crop(left_x, 0, left_x + 60, 80)
cropped_img = resized_image.execute_transforms(output_encoding=images.JPEG)
In my example it crops to the center of the image.
It assumes that the resized image is at least 60 pixels wide, but obviously you would have to add some checks to confirm this, because a user might not upload an image in the right size.
I used something else:
Resize the original image to your max height (80)
Store the resized (but complete/not cropped) image
Display it inside a <div> that has the following CSS: width: 60px; height: 80px; overflow: hidden;
That way it will show nicely in your list, but you can still display the complete resized picture on your user's profile page (looking at you code I imagine that's what you are trying to do, right?)

Resources