[I found this question asked once before on SO about a year ago on but it went unanswered so I am asking again (wasn't sure whether best practice was to create a new question or "bump" the existing one).]
I have a Xamarin Forms application which is receiving a stream of JPEGs over HTTP and I want to keep updating a single Image placeholder with their contents. The frame rate at which I receive the images is very slow by design (maybe 5 fps at most) as this is for a time-lapse photography project. I want to be able to show the stills as an animation (think: taking a photo of a plant once per hour and then "playing" all of the stills to create a lively animation of said plant).
The problem I am having is with "flicker" while swapping one image out for the next. I've tried a variety of approaches, including having two Images (one visible at a time) and only changing the visibility once I'm done loading the latest image (I think this is maybe a naive form of double-buffering?). Have also looked into Motion JPEG, HTTP Keep-Alive, and even using a WebView (I have a valid Motion JPEG endpoint that I can read from). Anyway, nothing that I've found so far has helped reduce the flicker and therefore the "animation" of the stills remains very "jerky" for lack of a better way to put it, with a momentary blank (white) pane between stills. Frankly speaking, it looks like crap.
Here is the gist of the code which fetches the next "frame" and updates the "player" image:
var url = $"{API_BASE_URL}/{SET_ID}/{_filenames[_currentFilenameIndex]}";
var imageBytes = await Task.Run(() => _httpClient.GetByteArrayAsync(url));
var imageBytesStream = new MemoryStream(imageBytes);
var timeComponents = _filenames[_currentFilenameIndex].Split('T')[1].Split('.')[0].Split('-');
var timeText = $"{timeComponents[0]}:{timeComponents[1]}:{timeComponents[2]}";
Device.BeginInvokeOnMainThread(
() =>
{
TimePlaceholder.Text = $"{timeText} (Image {_currentFilenameIndex + 1}/{_filenames.Count})";
ImagePlaceholder.Source = ImageSource.FromStream(() => imageBytesStream);
});
Any suggestions would be greatly appreciated.
how can I set height and width in scaling and can I depend on the image generated (quality and professional scale generation).
how can I set height and width in scaling
You can't. Specify a maxSize for each scaling.sizes entry and Fine Uploader will proportionally scale the image.
can I depend on the image generated (quality
Quality will be limited if you rely on the browser only. There is an entire section in the documentation that explains how you can generate higher-quality resizes by integrating a third-party resize library. I also discuss why you may or may not want to do this. From the documentation:
Fine Uploader's internal image resize code delegates to the drawImage
method on the browser's native CanvasRenderingContext2D object. This
object is used to manipulate a element, which represents a
submitted image File or Blob. Most browsers use linear interpolation
when resizing images. This can lead to extreme aliasing and moire
patterns which is a deal breaker for anyone resizing images for
art/photo galleries, albums, etc. These kinds of artifacts are
impossible to remove after the fact.
If speed is most important, and precise scaled image generation is not
paramount, you should continue to use Fine Uploader's internal scaling
implementation. However, if you want to generate higher quality scaled
images for upload, you should instead use a third-party library to
resize submitted image files, such as pica or limby-resize. As of
version 5.10 of Fine Uploader, it is extremely easy to integrate such
a plug-in into this library. In fact, Fine Uploader will continue to
properly orient the submitted image file and then pass a properly
sized to the image scaling library of your choice to receive
the resized image file, along with the original full-sized image file
drawn onto a for reference. The only caveat is that, due to
issues with scaling larger images in iOS, you may need to continue to
use Fine Uploader's internal scaling algorithm for that particular OS,
as other third-party scaling libraries most likely do not contain
logic to handle this complex case. Luckily, that is easy to account
for as well.
If you'd like to, for example, use pica to generate higher-quality
scaled images, simply pull pica into your project, and contribute a
scaling.customResizer function, like so:
scaling: {
customResizer: !qq.ios() && function(resizeInfo) {
return new Promise(function(resolve, reject) {
pica.resizeCanvas(resizeInfo.sourceCanvas, resizeInfo.targetCanvas, {}, resolve)
})
},
...
}
Is there some easy way to scale an image to a maximum size?
Looking for some some easy way to keep file sizes down and scale images that are uploaded from the app to max 640 width for example.
I have googled several solutions, from module Ti.ImageFactory to just put it into an ImageView with a size, and get the blob back again (which should make it scaled?). The Ti.ImageFactory module seems very old though, several years ago updated if you look at GIT. Also the zip files for download seems to be missing on git...
Ex.
Titanium.Media.openPhotoGallery({
success:function(event)
{
Ti.API.info('Our type was: '+event.mediaType);
if(event.mediaType == Ti.Media.MEDIA_TYPE_PHOTO)
{
// HERE event.media needs to be scaled to a max
// size... for example 2 MB data, or max 960 px
// width/height or something similar
uploadPhoto(event.media);
}
},
cancel:function()
{
Ti.API.info("Photo gallery cancel...");
},
error:function(err)
{
//Ti.API.error(err);
Ti.API.info("Err: "+err);
alert(L("AN_ERROR_OCCURRED"));
},
mediaTypes:[Ti.Media.MEDIA_TYPE_PHOTO]
});
What you are looking for is the function imageAsCropped or imageAsResized.
Let me know if you need Further help.
You can use the size property.
size : Dimensionreadonly
The size of the view in system units.
Although property returns a Dimension dictionary, only the width and
height properties are valid. The position properties--x and y--are
always 0.
To find the position and size of the view, use the rect property
instead.
The correct values will only be available when layout is complete. To
determine when layout is complete, add a listener for the postlayout
event.
Documentation Link
I ended up using ti.imagefactory module.
The zip files for android and ios I found here:
https://github.com/appcelerator-modules/ti.imagefactory/releases
Example can be found here:
https://github.com/appcelerator-modules/ti.imagefactory/blob/stable/ios/example/app.js
I used code from the examples in my app and it seems to work fine!
I wrote a little tool with node-webkit. One reason I chose node-webkit is the fact that it is easy to distribute your app to all major plattforms.
Something I would love to do now, is to resize a bunch of images located on the file storage.
I found plenty of packages which do this via ImageMagick. This would require the user to have ImageMagick installed, which is bad...
Using a webservice is no option. There can easily be around 600 images.
If there is no solution, I will only run that task IF imagemagick is installed.
You could use the canvas tag to resize your image.
Load the image in a canvas with the new size:
...
var tempCanvas = document.createElement('canvas');
tempCanvas.width = newWidth;
tempCanvas.height = newHeight;
var ctx = tempCanvas.getContext('2d');
var img = new Image();
img.src = imageSrc;
img.onload = function () {
ctx.drawImage(this, 0, 0);
};
Get resized image back from canvas:
...
var image = canvas.toDataURL('image/png');
image = image.replace('data:image/png;base64,', '');
var buffer = new Buffer(image, 'base64');
fs.writeFile('filename.png', buffer, function (error) {
if (error) {
// TODO handle error
}
});
...
In this example the resulting image will be a png. You can use as result type whatever node-webkit supports. If you have different image types as input and want to output in the same type you need to add some code that sets the correct mime type to canvas.toDataURL.
I am developing an image processing module without any runtime dependencies; which means your users don't need to have imagemagick installed. It's still at early stages, but already usable.
Part of the module is written in C++, so you'll have to make sure to npm install the module on each platform you package your app (better than telling your users to pre-install imagemagick, imho). node-webkit apps are distributed per-platform anyway, so it shouldn't be a problem. Note, though, that I haven't yet tested it with node-webkit,
With this module, resizing an image is as simple as:
image.batch().resize(200, 200).writeFile('output.jpg',function(err){
// done
});
More info at the module's Github repo.
my company has recently started to get problems with the image handling for our websites.
We have several websites (adult entertainment) that display images like dvd covers, snapshots and similar. We have about 100'000 movies and for each movie we have an average of 30 snapshots + covers. Almost every image has an additional version with blurring and overlay for non-members, this results in about 50 images per movie or a total of 5 million base images. Each of the images is available in several versions, depending on where it's placed on the page (thumbnail, original, small preview, not-so-small preview, small image in the top-list, etc.) which results in more images than i cared to count.
Now i had the idea to use a server to generate the images on-the-fly since it became quite clumsy to generate all the different images for all the different pages (as different pages sometimes even need different image sizes for basically the same task).
Does anyone know of an image processing server that can scale down images on-the-fly so we only need to provide the original images and the web guys can just request whatever size they need?
Requirements:
Very High performance (Several thousand users per day)
On-the-fly blurring and overlay creation
On-the-fly resize (with and without keeping aspect ratio)
Can handle millions of images
Must be able to read JPG, GIF, PNG and BMP and convert between them
Security is not that much of a concern as i.e. the unblurred images can already be reached by URL manipulation and more security would be nice but it's not required and frankly i stopped caring (After failing to get into my coworkers heads why (for our small reseller page) it's a bad idea to use http://example.com/view_image.php?filename=/data/images/01020304.jpg to display the images).
We tried PHP scripts to do this but the performance was too slow for this many users.
Thanks in advance for any suggestions you have.
I suggest you set up a dedicated web server to handle image resize and serve the final result. I have done something similar, although on a much smaller scale. It basically eliminates the process of checking for the cache.
It works like this:
you request the image appending the required size to the filename like http://imageserver/someimage.150x120.jpg
if the image exists, it will be returned with no other processing (this is the main point, the cache check is implicit)
if the image does not exist, handle the 404 not found via .htaccess and reroute the request to the script that generates the image of the required size
in the script specify the list of allowed sizes to avoid attacks like scripts requesting every possible size to shut your server down
keep this on a cookieless domain to minimize unnecessary traffic
EDIT: I don't think that PHP itself would slow the process much, as PHP scripting in this case is reduced to a minimum: the image scaling is done by a builtin library written in C. Whatever you do you'll have to use a library like this (GD or libmagick or so) so that's unavoidable. With my system at least you totally skip the overhead of checking the cache, thus further reducing PHP interaction. You can implement this on your existing server, so I guess it's a solution well suited for your budget.
Based on
We tried PHP scripts to do this but the performance was too slow for this many users.
I'm going to assume you weren't caching the results. I'd recommend caching the resulting images for a day or two (i.e. have your script check to see if the thumbnail has already been generated, if so use it, if it hasn't generate it on the fly).
This would improve performance dramatically as I'd imagine the main/start page probably has a lot more hits than random video X, thus when viewing the main page no images have to be created as they're cached. When User Y views Movie X, they won't notice the delay as much since it just has to generate that one page.
For the "On-the-fly resize" aspect - how important is bandwidth to you? I'd want to assume you're going through so much with movies that a few extra kb in images per request wouldn't do too much harm. If that's the case, you could just use larger images and set the width and height and let the browser do the scaling for you.
The ImageCache and Image Exact Sizes solutions from the Drupal community might do this, and like most solutions OSS use the libraries from ImageMagik
There are some AMI images for Amazons EC2 service to do image scaling. It used Amazon S3 for image storage, original and scales, and could feed them through to Amazons CDN service (Cloud Front). Check on EC2 site for what's available
Another option is Google. Google docs now supports all file types, so you can load the images up to a Google docs folder, and share the folder for public access. The URL's are kind of long e.g.
http://lh6.ggpht.com/VMLEHAa3kSHEoRr7AchhQ6HEzHVTn1b7Mf-whpxmPlpdrRfPW216UhYdQy3pzIe4f8Q7PKXN79AD4eRqu1obC7I
Add the =s paramter to scale the image, cool! e.g. for 200 pixels wide
http://lh6.ggpht.com/VMLEHAa3kSHEoRr7AchhQ6HEzHVTn1b7Mf-whpxmPlpdrRfPW216UhYdQy3pzIe4f8Q7PKXN79AD4eRqu1obC7I=s200
Google only charge USD5/year for 20GB. There is a full API for uploading docs etc
Other answers on SO
How best to resize images off-server
Ok first problem is that resizing an image with any language takes a little processing time. So how do you support thousands of clients? We'll you cache it so you only have to generate the image once. The next time someone asks for that image, check to see if it has already been generated, if it has just return that. If you have multiple app servers then you'll want to cache to a central file-system to increase your cache-hit ratio and reduce the amount of space you will need.
In order to cache properly you need to use a predictable naming convention that takes into account all the different ways that you want your image displayed, i.e. use something like myimage_blurred_320x200.jpg to save a jpeg that has been blurred and resized to 300 width and 200 height, etc.
Another approach is to sit your image server behind a proxy server that way all the caching logic is done automatically for you and your images are served by a fast, native web server.
Your not going to be able to serve millions of resized images any other way. That's how Google and Bing maps do it, they pre-generate all the images they need for the world at different pre-set extents so they can provide adequate performance and be able to return pre-generated static images.
If php is too slow you should consider using the 2D graphic libraries from Java or .NET as they are very rich and can support all your requirements. To get a flavour of the Graphics API here is a method in .NET that will resize any image to the new width or height specified. If you omit a height or width, it will resize maintaining the right aspect ratio. Note Image can be a created from a JPG, GIF, PNG or BMP:
// Creates a re-sized image from the SourceFile provided that retails the same aspect ratio of the SourceImage.
// - If either the width or height dimensions is not provided then the resized image will use the
// proportion of the provided dimension to calculate the missing one.
// - If both the width and height are provided then the resized image will have the dimensions provided
// with the sides of the excess portions clipped from the center of the image.
public static Image ResizeImage(Image sourceImage, int? newWidth, int? newHeight)
{
bool doNotScale = newWidth == null || newHeight == null; ;
if (newWidth == null)
{
newWidth = (int)(sourceImage.Width * ((float)newHeight / sourceImage.Height));
}
else if (newHeight == null)
{
newHeight = (int)(sourceImage.Height * ((float)newWidth) / sourceImage.Width);
}
var targetImage = new Bitmap(newWidth.Value, newHeight.Value);
Rectangle srcRect;
var desRect = new Rectangle(0, 0, newWidth.Value, newHeight.Value);
if (doNotScale)
{
srcRect = new Rectangle(0, 0, sourceImage.Width, sourceImage.Height);
}
else
{
if (sourceImage.Height > sourceImage.Width)
{
// clip the height
int delta = sourceImage.Height - sourceImage.Width;
srcRect = new Rectangle(0, delta / 2, sourceImage.Width, sourceImage.Width);
}
else
{
// clip the width
int delta = sourceImage.Width - sourceImage.Height;
srcRect = new Rectangle(delta / 2, 0, sourceImage.Height, sourceImage.Height);
}
}
using (var g = Graphics.FromImage(targetImage))
{
g.SmoothingMode = SmoothingMode.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(sourceImage, desRect, srcRect, GraphicsUnit.Pixel);
}
return targetImage;
}
In the time that this question has been asked, a few companies have sprung up to deal with this exact issue. It is not an issue that's isolated to you or your company. Many companies reach the point where they need to look for a more permanent solution for their image processing needs.
Services like imgix serve as a proxy and CDN for image operations like resizing and applying overlays. By manipulating the URL, you can apply different transformations to each image. imgix serves billions of requests per day.
You can also stand up services on your own and put them behind a CDN. Open source projects like imageproxy are good for this. This puts the burden of maintenance on your operations team.
(Disclaimer: I work for imgix.)
What you are looking for is best matched by Thumbor http://thumbor.readthedocs.org/en/latest/index.html , which is open source, backed by a huge company (means it will not disappear tomorrow), and ships with a lot of nice features like detecting what is important on an image when cropping.
For low-cost plus CDN I'd suggest to combine it with Cloudfront and AWS storage, or a comparable solution with a free CDN like Cloudflare. These might not be the best performing CDN providers, but at least still perform better than one server and also offload your image server on the cheap. Plus, it will save you a TON of bandwidth cost.
If each different image is uniquely identifiable by a single URL then I'd simply use a CDN such as AKAMAI. Let your PHP script do the job and let AKAMAI handle the load.
Since this kind of business doesn't usually have budget problems, that'd be the only place I'd look at.
Edit: that works only if you do find a CDN that will serve this kind of content for you.
This exact same problem is now being solved by image resize services dedicated to this task. They provide following features:
In built CDN - you need not worry about image distribution
Image resize on the fly - any size needed is available
No storage needed - you just store base image and all variants are handled by service
Ecosystem libraries - you can just include javascript and your job is done for all devices and all browsers.
One such service is Gumlet. You can also try some open source alternative like nginx plugin which can also resize image on the fly.
(I work for Gumlet.)