Slowness loading large (2M) images into listWidget - image

I have a simple QlistWidget where I'm loading images in one call using this code:
ui.listWidgetImages->setIconSize(QSize(60, 60));
QStringList::const_iterator i = filenames.constBegin(); // QStringList that holds the images paths
while (i != filenames.constEnd()) {
QString value = *i;
QListWidgetItem *standardItemnew = new QListWidgetItem(value, ui.listWidgetImages);
standardItemnew->setIcon(QIcon(value));
++i;
}
I guess the slowness is the result of scalling down the images to 60/60 size but, is there any way to speed up the process?

The fastest soluton would be to pre-generate the thumbnails or use thumbnails already embedded in the image.
If that's not feasible your only option may be to us Qt's multithreading. There are two sides to this. To start with the entire task of populating the list could be hived off into a separate thread so that the application doesn't lock during the process. More ambitiously, if the users have multi-core systems you might consider loading and scaling each image in a separate thread.

Related

Preload (all) image assets in a Flutter app

I would like an easy approach to preload/cache all of my static image assets so that they can be rendered/served without a delay.
I've seen that there is a precacheImage() call that can be used to pre-load/cache the AssetImage. This needs a context and it is recommended to call this in the didChangeDependencies() override.
Shouldn't there be a way to make this easier and more general? My app uses a total of 1.5 MB of image data (and I've included 2.0x and 3.0x upscaled versions in that number). PNG images that are 50 KB (and no upscaled versions) takes a noticeable amount of time to display, maybe 300-600ms on both emulator and fast devices. These are local assets, not fetched over the network. I find that irritating and I'm frustrated that there isn't a better way to handle this?
I've also seen the tip to use FadeInImage but again - it's not really what I'm looking for.
I'm displaying the image in a stateless widget (a custom button). It's not possible to use precacheImage in a stateless widget afaik. So I'd need to build the Image.asset() in my parent widget, call precacheImage and then pass the image widget to my stateless widget and render it in build - this is cumbersome.
Furthermore, the images will be displayed in different places (different parent widgets). Sometimes the image widgets differ in size between widgets and since size is parameters to Image.asset() I guess I would need to precache each unique size and pass these precached image widgets around. Isn't it possible to tell Flutter to "cache" the data of the PNG so that when the Image.asset is requested it reads the PNG from cache - without having to pass around precached image widgets?
I would like a "precacheAllImageAssets()call or callprecacheImage()` with a string so that each Image.asset() that references that same asset would be cached.
I guess that Flutter internally caches the image widget (including it's size and other properties) as some internal render object that is cached. Thus pre-caching two different sizes of the same image would require two different caches. With that being said - I'd still want a precacheAllImageAssets() call that could at least read the PNG data into memory and just serve it quicker even if would need to do some processing to get the PNG data to an actual widget with a size before it could be rendered. With such a cache I could maybe get a render delay of < 50 ms instead of the current 300-600 ms.
Any idea if this is possible? If not possible - am I missing something obvious or could this be a (likely) future improvement of the Flutter framework?
Here is my similar precacheAllImageAssets(), but you need to list all image path by yourself.
final List _allAsset = [
///tabbar
'images/tabbar/tabar_personal.png',
'images/tabbar/tabar_personal_slt.png',
'images/tabbar/tabar_home.png',
'images/tabbar/tabar_home_slt.png',
'images/...'
'images/...'
}
void main() {
final binding = WidgetsFlutterBinding.ensureInitialized();
binding.addPostFrameCallback((_) async {
BuildContext context = binding.renderViewElement;
if(context != null)
{
for(var asset in _allAsset)
{
precacheImage(AssetImage(asset), context);
}
}
});
}
UPDATE: after some research I've figured out that previous version of my answer was not correct. Here is relevant one (you can see old one in edit history).
You do not need to use same ImageProvider for images to precache. So you can run precacheImage() at init time and then create another image with same path and it is gonna be obtained from cache (if it was not cleared one way on another).
Internally precacheImage() uses ImageProvider.obtainKey() which is pair of (imagePath, scale) as a key to store image in in-memory cache. So as long as you are using same key it does not matter which instance of ImageProvider/Image you are using.
For futher insights you can inspect ImageCache documentation. Specifically, take a look at putIfAbsent() method as it's main caching endpoint. To understand how images generate their key (at which they are stored in ImageCache) try to start with ImageProvider class and then look into it's implementations.

Xamarin.Mac PdfView performance problems

I'm creating an app to visualize some experimental data (x,y plots with multiple series) where the primary goal is to generate a pdf file which conforms to scientific publication rules. The pdf generation works well and I can also display the pdf in a PdfKit PdfView. However, when I try to show large pdf files in the app (data series with lots of points (as in 20000)), some background thread will spend minutes (3-4) on generating some sort of cached version which the PdfView uses for faster zoom rendering.
I can get around the issue by setting the PdfView.Document as an empty pdf document and then adding a page afterwards. The PdfView will cache a blank page but I won't spend minutes at 100% CPU usage trying to generate a cached version. However, this introduced another issue, if there is no cached version, the zoom operation will be less pleasant than what is desired.
In addition, I have some sliders which affect the pdf result and the require very fast updates of the displayed pdf.
Is there a better way of displaying pdf files (data)? It would be best if the method allows zooming in the document.
Very slow for large pdf files:
PDFPlotView.Document = pdf;
Fast, but no cached version:
PDFPlotView.Document = new PdfDocument();
PDFPlotView.Document.InsertPage(pdf.GetPage(0), 0);
I've also tried generating a low res image from the pdf and then trying to use that image for cache generation, but it appears that there is a known bug which causes the pdf to become blank:
using (var context = new CGBitmapContext(null, (int)rect.Width, (int)rect.Height, 8, 0, CGColorSpace.CreateDeviceRGB(), CGBitmapFlags.NoneSkipLast)
{
InterpolationQuality = CGInterpolationQuality.None
})
{
context.SetFillColor(new CGColor(1, 1, 1, 1));
context.FillRect(rect);
context.ScaleCTM(1, 1);
context.DrawPDFPage(pdf.Document.GetPage(0));
img = context.ToImage();
}
PdfDocument lowrespdf = new PdfDocument();
NSImage cache = new NSImage(img, rect.Size);
PdfPage page = new PdfPage(cache);
lowrespdf.InsertPage(page, 0);
[UPDATE] Performance issue appears to be related not to the number of
data points, but rather to the length of a single path in the PDF file.
Splitting a problematic data series up in new lines every 1000 data
point results in a cache time of a few seconds (max) compared to a few
minutes for the 25000 data point line.

Best way to preload SVG image tags?

I'm building an SVG-based visualization that (partially) relies on showing many images in quick succession. The images can't be fetched fast enough from the network, so they must be preloaded.
My understanding is that SVG doesn't properly cache image tags, at least in major browsers. So JavaScript preloading librairies and techniques (eg. this SO question) won't work. (I could resort to using layered HTML img tags, but because of the specifics of my application, I would like to stick to pure SVG as much as possible)
I see two options:
Encoding the PNG image data as base64, storing it in memory as strings and using the strings to iteratively populate image tags using data:image/png;base64.
Layering many SVG groups on top of each other with all but one set to display: none or visibility: hidden and iteratively unhiding the appropriate group. However, I believe it won't be possible to programatically detect that all images have finished preloading.
What's the best way to preload the image data? Perhaps I've missed an easier option.
I'm not familiar enough with the underlying mechanics of web browsers to know if this will work with svg image tags, but I had success caching images with new Image():
//download low quality images
var imageArray = []
for (var i = 0; i < 600; i++){
imageArray[i] = new Image();
imageArray[i].src = moviePath + (i + 1) + '.jpg.t';
imageArray[i].onload = function(){
var i = this.src.split(movieName + '/')[1].split(".")[0];
d3.select("#bar" + i).style("stroke", 'rgb(' + colors[i].rgb + ')');
}
}
To show an image, I just set the src of the displayed image to one that was already loaded and the browser loads it from its cache.
There is another small trick used later in the source - show a low quality image first and starting loading a high quality one only after a short timeout passes without another image being selected. Then, after the high quality image has loaded, show it only if the same image is still selected.
No idea if these are best practices or anything, but it worked reasonably well.

Can be smoothing image in a loaded SWF?

I'm trying to load an SWF into another in AS3/Haxe. The loaded SWF contains some images - but only on some Shape.graphics elements. (Like graphics.beginBitmapFill(); ...)
This images are not smoothed, and jaggy.
Can this images be smoothed anyhow during runtime?
Any hack interested! :)
Thanks in advance!
Tom
Update: Sorry, but I forget to mention, that I'm loading more AS2-SWFs (AVM1) into one AS3-SWF (AVM2) with AVM2Loader, which hack the loaded bytes, and convert the AVM1 SWFs into AVM2 - it works very well. :)
So, in these SWFs I need to find the images/bitmaps, but only found the Shapes, which graphics elements has the 'images'. If I clear this graphics, then all images are gone, so I think, the images are in some graphics.beginBitmapFill(...);, without smoothing. I want to reach them, and switch smoothing on at runtime, if possible.
(Sorry, if the first time I was not enough clear.)
Edit (Jan 23 '14): I found solution for it. It is not fast, and required Flash Player 11.6. Every MovieClip graphics properties has a new readGraphicsData function, which give all the graphics commands (Vector IGraphicsData) to draw the whole MC. And iterate in these commands, if I change every bitmapFill command smooth parameter to true, and redraw the MC, it will be smoothed, and nice.
That's it. Not fast, but working.
I found solution for it. It is not fast, and required Flash Player 11.6. Every MovieClip graphics properties has a new readGraphicsData function, which give all the graphics commands (Vector IGraphicsData) to draw the whole MC. And iterate in these commands, if I change every bitmapFill command smooth parameter to true, and redraw the MC, it will be smoothed, and nice.
That's it. Not fast, but working.
function onLoad(event):Void
{
pic.forceSmoothing = true;
}
Smoothing is a property of bitmaps that's off by default.
var image = new Bitmap(bitmapData);
image.smoothing = true;
Typically, your bitmapData will be in the loader.content.bitmapData when loading externally, but it's up to you were you've stored it.
Update:
If you want to smooth all images in a loaded SWF without any knowledge of the structure of the SWF, then you'll have to recursively dig through the hiarchy of that SWF, and depending on whether or not the object is a Bitmap, turn on smoothing.
function recursivelySmooth(obj):void {
for (var i:int = 0; obj.getChildAt(i); i++) {
var item:* = obj.getChildAt(i);
if (item is Bitmap) {
item.smoothing = true;
} else if (item.hasOwnProperty("numChildren") == true) {
recursivelySmooth(item);
}
}
}
This was written freehand, so you may have to doublecheck everything is correct, but that's the basic idea. Just call recursivelySmooth() on your swf, and it'll dig through all objects that can have child elements and smooth them.

Serving Images with on-the-fly resize

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.)

Resources