Yii2 - Image upload and resizing,ajax upload support extension - yii2

Is there any good image uploading and resize extension for yii2; I don't want to use kartik because since I had a problem I've not gotten any help to understand where the problem is, same situation with Illustrated behavior so I am stack in my project.
What I want is multiple image uploading,ajax support(even for old browser if not to turn to normal file input), image resizing keeping good quality,allowing one image to be saved in different sizes and Preview the file when selected from client side(not obliged).

Usually I use image magick direcly.
Check if these two functions can be useful for you:
public static function generateImagesScaledAndCropped($inputFile, $outputFile, $params)
{
$imageMagickConvert = \Yii::$app->params['imagick.convert'];
$cmd = sprintf("%s %s -resize %dx%d^ -gravity Center -crop %dx%d+0+0 %s", $imageMagickConvert, $inputFile, $params['edge'], $params['edge'], $params['edge'], $params['edge'], $outputFile);
exec($cmd);
}
public static function generateImagesScaledByWidth($inputFile, $outputFile, $params)
{
$imageMagickConvert = \Yii::$app->params['imagick.convert'];
$cmd = sprintf("%s %s -resize %d %s", $imageMagickConvert, $inputFile, $params['width'], $outputFile);
exec($cmd);
}
Params are:
<?php
return [
'imagick.convert' => '/usr/bin/convert',
'imagick.composite' => '/usr/bin/composite',
];

I use Imagine as abstract layer on Imagine library which
uses populars php libraries to work with images
http://www.yiiframework.com/doc-2.0/ext-imagine-index.html

Related

Yii2 render image in browser without image tag using yii2-imagine

I'm using yii2-imagine
$imagine = yii\imagine\Image::getImagine();
Imagine->open('path/watermark.jpg')->show('jpg');
My problem is it not show the image, it show that:
����JFIF��>CREATOR: gd-jpeg v1.0 (using IJG JPEG v90), default quality ��C $.' ",#(7),01444'9=82<.342��C 2!!22222222222222222222222222222222222222222222222222����"�� ���}!1AQa"q2���#B��R��$3br� %&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz��������������������������������������������������������������������������� ���w!1AQaq"2�B���� #3R�br� $4�%�
Any idea?
You need to use the getImagine() function first to invoke the GD or Imagick which ever available instance then call ->open() and ->show() on the object. Moreover, you need to provide the $options for the image to display too. You can copy paste the following code inside an action in your controller and can see the result image. I just tested on my local system, and it is in working, just remember to provide valid path to the $source variable
use yii\imagine\Image;
$source="/path/to/your/image.jpg";
$imagine = new Image();
$options = array(
'resolution-units' => \Imagine\Image\ImageInterface::RESOLUTION_PIXELSPERINCH,
'resolution-x' => 300,
'resolution-y' => 300,
'jpeg_quality' => 100,
);
echo $imagine->getImagine()->open($source)->show('jpg',$options);
Apart from the above solution that displays the image in the browser if you want to display the image inside the img tag you can base64_encode the raw image data returned from the open() method and provide into the tag like below.
echo '<img src="data:image/jpeg;base64,'.base64_encode($imagine->getImagine()->open($source)).'" >';
Hope it helps

Limit rendered image size in icepdf

While rendering a bunch of PDFs to images, icepdf seemingly randomly bombs out with an OutOfMemoryError. Trying to track this down I find two things:
Close to the OOM it rendered an A0 page or similarly large document pages
With eclipse memory analyzer I find 1/2GB images in memory.
This suggests to limit the output image size to something managable. I wonder what the easiest way is to do this?
I looked at icepdf's Page object but there it is strongly recommended to just always use Page.BOUNDARY_CROPBOX and other uses seem not to be documented in the Javadoc.
How can I limit the output image size of Document.getPageImage or what other measure could I use to prevent the OOM (other than just increasing the Xmx, which I can't). Reduction of image quality is an option. But it should apply only to "oversize" images, not to all.
I tried already to use a predefined image using Document.paintPage(), but this was not sufficient.
Debug finally allowed me to zoom in on a document that is problematic. I get a log like:
2016-12-09T14:23:35Z DEBUG class org.icepdf.core.pobjects.Document 1 MEMFREE: 712484296 of 838860800
2016-12-09T14:23:35Z DEBUG class org.icepdf.core.pobjects.Document 1 LOADING: ..../F1-2.pdf
2016-12-09T14:23:37Z WARN class org.icepdf.core.pobjects.graphics.ScaledImageReference 1 Error loading image: 9 0 R Image stream= {Type=XObject, Length=8 0 R, Filter=FlateDecode, ColorSpace=DeviceGray, Decode=[1, 0], Height=18676, Width=13248, Subtype=Image, BitsPerComponent=1, Name=Im1} 9 0 R
so this would be Height=18676, Width=13248 which is really huge.
I guess that the OOM happens already during loading of the image, so later scaling does not help. Also it seems that the property org.icepdf.core.imageReference=scaled does not hit early enough.
For me it would be fine to just ignore oversized images like this. Any chance?
Image loading is by far the most memory expensive memory task when decoding PDF content. At this time there isn't an esasy way to turn off image loading for really large image however I'll give you a few code hints if you want to implement this your self.
The ImageReferenceFactory.java class is the factory behind the system property org.icepdf.core.imageReference, you'll see that the default for getImageReferenced() is ImageStreamReference. You can create a new ImageReference type like this:
public static org.icepdf.core.pobjects.graphics.ImageReference
getImageReference(ImageStream imageStream, Resources resources, GraphicsState graphicsState,
Integer imageIndex, Page page) {
switch (scaleType) {
case SCALED:
return new ScaledImageReference(imageStream, graphicsState, resources, imageIndex, page);
case SMOOTH_SCALED:
return new SmoothScaledImageReference(imageStream, graphicsState, resources, imageIndex, page);
case MIP_MAP:
return new MipMappedImageReference(imageStream, graphicsState, resources, imageIndex, page);
case SKIP_LARGE:
return new SkipLargeImageReference(imageStream, graphicsState, resources, imageIndex, page);
default:
return new ImageStreamReference(imageStream, graphicsState, resources, imageIndex, page);
}
}
Next you can extend the class ImageStreamReference with your new SkipLargeImageReference class. Then override the call() method as follows and it will skip the loading of any image over the defined MAX_SIZE .
public BufferedImage call() {
BufferedImage image = null;
if (imageStream.getWidth() < MAX_SIZE && imageStream.getHeight() < MAX_SIZE){
long start = System.nanoTime();
try {
image = imageStream.getImage(graphicsState, resources);
} catch (Throwable e) {
logger.log(Level.WARNING, "Error loading image: " + imageStream.getPObjectReference() +
" " + imageStream.toString(), e);
}
long end = System.nanoTime();
notifyImagePageEvents((end - start));
return image;
}
return null;
}
On a side note: To minimize the the amount of memory needed to decode an image make sure you are using org.icepdf.core.imageReference=default as this will decode the image only once. org.icepdf.core.imageReference=scaled will actually decode the image at full size and then do the scale which can create a very large memory spike. We are experimenting with NIO's direct ByteBuffers which looks promising to moving the decode memory usage off the heap, so hopefully this will get better in the future.

LibTiff.NET append mode bug?

I've started using LibTiff.NET for writing tiff IPTC tags lately and discovered strange behavior on some files that i have here. I'm using sample code that ships with LibTiff.NET binaries, and it works fine with most of the images, but some files are having image data corruption after these lines:
class Program
{
private const TiffTag TIFFTAG_GDAL_METADATA = (TiffTag)42112;
private static Tiff.TiffExtendProc m_parentExtender;
public static void TagExtender(Tiff tif)
{
TiffFieldInfo[] tiffFieldInfo =
{
new TiffFieldInfo(TIFFTAG_GDAL_METADATA, -1, -1, TiffType.ASCII,
FieldBit.Custom, true, false, "GDALMetadata"),
};
tif.MergeFieldInfo(tiffFieldInfo, tiffFieldInfo.Length);
if (m_parentExtender != null)
m_parentExtender(tif);
}
public static void Main(string[] args)
{
// Register the extender callback
// It's a good idea to keep track of the previous tag extender (if any) so that we can call it
// from our extender allowing a chain of customizations to take effect.
m_parentExtender = Tiff.SetTagExtender(TagExtender);
string destFile = #"d:\00000641(tiffed).tif";
File.Copy(#"d:\00000641.tif", destFile);
//Console.WriteLine("Hello World!");
// TODO: Implement Functionality Here
using (Tiff image = Tiff.Open(destFile, "a"))
{
// we should rewind to first directory (first image) because of append mode
image.SetDirectory(0);
// set the custom tag
string value = "<GDALMetadata>\n<Item name=\"IMG_GUID\">" +
"817C0168-0688-45CD-B799-CF8C4DE9AB2B</Item>\n<Item" +
" name=\"LAYER_TYPE\" sample=\"0\">athematic</Item>\n</GDALMetadata>";
image.SetField(TIFFTAG_GDAL_METADATA, value);
// rewrites directory saving new tag
image.CheckpointDirectory();
}
// restore previous tag extender
Tiff.SetTagExtender(m_parentExtender);
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
}
After opening i see mostly blank white image or multiple black and white lines instead of text that have been written there (i don't need to read\write tags to produce this behavior). I noticed this happens when image already has a custom tag (console window alerts about it) or one of tags have got 'bad value' (console window in this case says 'vsetfield:%pathToTiffFile%: bad value 0 for "%TagName%" tag').
Original image: http://dl.dropbox.com/u/1476402/00000641.tif
Image after LibTiff.NET: http://dl.dropbox.com/u/1476402/00000641%28tiffed%29.tif
I would be grateful for any help provided.
You probably should not use CheckpointDirectory method for files opened in append mode. Try using RewriteDirectory method instead.
It will rewrite the directory, but instead of place it at it's old
location (as WriteDirectory() would) it will place them at the end of
the file, correcting the pointer from the preceeding directory or file
header to point to it's new location. This is particularly important
in cases where the size of the directory and pointed to data has
grown, so it won’t fit in the space available at the old location.
Note that this will result in the loss of the previously used
directory space.

saving google map to image from a browser component window inside a c# application

I wanted to save the google map into an image from a webpage.
while i was searching for that i got this program.
http://www.codres.de/downloads/gms.exe[^]
besides other alternatives like print screen i wanted to use a program or map api which can save a specified dimension of google map instead of the screen.
i have used browser component in c# for http access and for displaying certain webpages.
I want to know whether there are options to capture the browser screen to image using any c# functionality or even the browser component would have given such options. just a guess.
i would like to have answers, suggestions on how to capture the map with custom dimension and zoom size to an image.
I used this to get captcha Image from the current page, so you can use similar code just amend the imageID to point to the google map image and use this solution for zooming.
public string newsavefunction(WebBrowser webBrowser1)
{
IHTMLDocument2 doc = (IHTMLDocument2)webBrowser1.Document.DomDocument;
IHTMLControlRange imgRange = (IHTMLControlRange)((HTMLBody)doc.body).createControlRange();
string imagename = string.Empty;
try
{
foreach (IHTMLImgElement img in doc.images)
{
imgRange.add((IHTMLControlElement)img);
imgRange.execCommand("Copy", false, null);
using (Bitmap bmp = (Bitmap)Clipboard.GetDataObject().GetData(DataFormats.Bitmap))
{
bmp.Save(#"F:\captchaimages\captchapic.jpg");
}
imagename = img.nameProp;
break;
}
}
catch (System.Exception exp)
{ }
return imagename;
}

With a browser, how do I know which decimal separator does the operating system use?

I'm developing a web application.
I need to display some decimal data correctly so that it can be copied and pasted into a certain GUI application that is not under my control.
The GUI application is locale sensitive and it accepts only the correct decimal separator which is set in the system.
I can guess the decimal separator from Accept-Language and the guess will be correct in 95% cases, but sometimes it fails.
Is there any way to do it on server side (preferably, so that I can collect statistics), or on client side?
Update:
The whole point of the task is doing it automatically.
In fact, this webapp is a kind of online interface to a legacy GUI which helps to fill the forms correctly.
The kind of users that use it mostly have no idea on what a decimal separator is.
The Accept-Language solution is implemented and works, but I'd like to improve it.
Update2:
I need to retrive a very specific setting: decimal separator set in Control Panel / Regional and Language Options / Regional Options / Customize.
I deal with four kinds of operating systems:
Russian Windows with a comma as a DS (80%).
English Windows with a period as a DS (15%).
Russian Windows with a period as a DS to make poorly written English applications work (4%).
English Windows with a comma as a DS to make poorly written Russian applications work (1%).
All 100% of clients are in Russia and the legacy application deals with Russian goverment-issued forms, so asking for a country will yield 100% of Russian Federation, and GeoIP will yield 80% of Russian Federation and 20% of other (incorrect) answers.
Here is a simple JavaScript function that will return this information. Tested in Firefox, IE6, and IE7. I had to close and restart my browser in between every change to the setting under Control Panel / Regional and Language Options / Regional Options / Customize. However, it picked up not only the comma and period, but also oddball custom things, like the letter "a".
function whatDecimalSeparator() {
var n = 1.1;
n = n.toLocaleString().substring(1, 2);
return n;
}
function whatDecimalSeparator() {
var n = 1.1;
n = n.toLocaleString().substring(1, 2);
return n;
}
console.log('You use "' + whatDecimalSeparator() + '" as Decimal seprator');
Does this help?
Retrieving separators for the current or a given locale is possible using Intl.NumberFormat#formatToParts.
function getDecimalSeparator(locale) {
const numberWithDecimalSeparator = 1.1;
return Intl.NumberFormat(locale)
.formatToParts(numberWithDecimalSeparator)
.find(part => part.type === 'decimal')
.value;
}
It only works for browsers supporting the Intl API. Otherwise it requires an Intl polyfill
Examples:
> getDecimalSeparator()
"."
> getDecimalSeparator('fr-FR')
","
Bonus:
We could extend it to retrieve either the decimal or group separator of a given locale:
function getSeparator(locale, separatorType) {
const numberWithGroupAndDecimalSeparator = 1000.1;
return Intl.NumberFormat(locale)
.formatToParts(numberWithGroupAndDecimalSeparator)
.find(part => part.type === separatorType)
.value;
}
Examples:
> getSeparator('en-US', 'decimal')
"."
> getSeparator('en-US', 'group')
","
> getSeparator('fr-FR', 'decimal')
","
> getSeparator('fr-FR', 'group')
" "
Ask the user, do not guess. Have a setting for it in your web application.
Edited to add:
I think it is ok to guess the default setting that works ok, say, 95% of the time. What I meant was that the user should still be able to override whatever guesses the software made. I've been frustrated too many times already when a software tries to be too smart and does not allow to be corrected.
Why not
console.log(0.1.toLocaleString().replace(/\d/g, ''));
function getDecimalSeparator() {
//fallback
var decSep = ".";
try {
// this works in FF, Chrome, IE, Safari and Opera
var sep = parseFloat(3/2).toLocaleString().substring(1,2);
if (sep === '.' || sep === ',') {
decSep = sep;
}
} catch(e){}
return decSep;
}
I can guess the decimal separator from
Accept-Language and the guess will be
correct in 95% cases, but sometimes it
fails.
This is IMO the best course of action. In order to handle the failures, add a link to set it manually next to the display area.
Using other people answers I compiled the following decimal and thousand separators utility functions:
var decimalSeparator = function() {
return (1.1).toLocaleString().substring(1, 2);
};
var thousandSeparator = function() {
return (1000).toLocaleString().substring(1, 2);
};
Enjoy!
Similar to other answers, but compressed as a constant:
const decimal=.1.toLocaleString().substr(1,1); //returns "." in Canada
Also, to get the thousands separator:
const thousands=1234..toLocaleString().substr(1,1); //returns "," in Canada
Just place the code at the top of your JS and then call as required to return the symbol.
For example (where I live), to remove commas from "1,234,567":
console.log( "1,234,567".replaceAll(thousands,"") ); //prints "1234567" to console.
I think you have to rely on JavaScript to give you the locale settings.
But apparently JS doesn't have direct access to this information.
I see Dojo Toolkit relies on an external database to find the locale information, although it might not take in account setting changes, for example.
Another workaround I see is to have a small silent Java applet that query this information from the system, and JavaScript to get it out of Java.
I can give more information if you don't know how to do it (if you want to go this convoluted route, of course).
[EDIT]
So I updated my knowledge of localization support in Java...
Unlike what I thought originally, you won't have directly the decimal separator or thousand separator characters directly, like you would do with line separator or path separator: instead Java offers APIs to format the numbers or dates you provide.
Somehow, it makes sense: in Europe you often put the currency symbol after the number, some countries (India?) have a more complex rule to separate digits, etc.
Another thing: Java correctly finds the current locale from the system, but doesn't take information from there (perhaps for above reasons). Instead it uses its own set of rules. So if you have a Spanish locale where you replaced decimal separator with an exclamation sign, Java won't use it (but perhaps neither your application, anyway...).
So I am writing an applet exposing a service (functions) to JavaScript, allowing to format numbers to the current locale. You can use it as such, using JavaScript to format numbers on the browser. Or you can just feed it with some sample number and extract the symbols from there, using them locally or feeding them back to the server.
I finish and test my applet and post it there soon.
OK, I have something to show, more a proof of concept than a finished product, but because of lack of precise specifications, I leave it this way (or I will over-engineer it). I post in a separate message because it will be a bit long.
I took the opportunity to try a bit more jQuery...
The Java code:
GetLocaleInfo.java
import java.applet.*;
import java.util.Locale;
import java.text.*;
public class GetLocaleInfo extends Applet
{
Locale loc;
NumberFormat nf;
NumberFormat cnf;
NumberFormat pnf;
// For running as plain application
public static void main(String args[])
{
final Applet applet = new GetLocaleInfo();
applet.init();
applet.start();
}
public void init() // Applet is loaded
{
// Use current locale
loc = Locale.getDefault();
nf = NumberFormat.getInstance();
cnf = NumberFormat.getCurrencyInstance();
pnf = NumberFormat.getPercentInstance();
}
public void start() // Applet should start
{
// Following output goes to Java console
System.out.println(GetLocaleInformation());
System.out.println(nf.format(0.1));
System.out.println(cnf.format(1.0));
System.out.println(pnf.format(0.01));
}
public String GetLocaleInformation()
{
return String.format("Locale for %s: country=%s (%s / %s), lang=%s (%s / %s), variant=%s (%s)",
loc.getDisplayName(),
loc.getDisplayCountry(),
loc.getCountry(),
loc.getISO3Country(),
loc.getDisplayLanguage(),
loc.getLanguage(),
loc.getISO3Language(),
loc.getDisplayVariant(),
loc.getVariant()
);
}
public String FormatNumber(String number)
{
double value = 0;
try
{
value = Double.parseDouble(number);
}
catch (NumberFormatException nfe)
{
return "!";
}
return nf.format(value);
}
public String FormatCurrency(String number)
{
double value = 0;
try
{
value = Double.parseDouble(number);
}
catch (NumberFormatException nfe)
{
return "!";
}
return cnf.format(value);
}
public String FormatPercent(String number)
{
double value = 0;
try
{
value = Double.parseDouble(number);
}
catch (NumberFormatException nfe)
{
return "!";
}
return pnf.format(value);
}
}
An example of HTML page using the above applet:
GetLocaleInfo.html
<!-- Header skipped for brevity -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.js"></script>
<script type="text/javascript">
var applet;
$(document).ready(function()
{
applet = document.getElementById('LocaleInfo');
$('#Results').text(applet.GetLocaleInformation());
});
</script>
<script type="text/javascript">
function DoFormatting()
{
$('table.toFormat').each(function()
{
var table = $(this);
$('td', table).each(function(cellId)
{
var val = $(this);
if (val.is('.number'))
{
val.text(applet.FormatNumber(val.text()));
}
else if (val.is('.currency'))
{
val.text(applet.FormatCurrency(val.text()));
}
else if (val.is('.percent'))
{
val.text(applet.FormatPercent(val.text()));
}
});
});
}
</script>
</head>
<body>
<div id="Container">
<p>Page to demonstrate how JavaScript can get locale information from Java</p>
<div id="AppletContainer">
<object classid="java:GetLocaleInfo.class"
type="application/x-java-applet" codetype="application/java"
name="LocaleInfo" id="LocaleInfo" width="0" height="0">
<param name="code" value="GetLocaleInfo"/>
<param name="mayscript" value="true"/>
<param name="scriptable" value="true"/>
<p><!-- Displayed if object isn't supported -->
<strong>This browser does not have Java enabled.</strong>
<br>
<a href="http://java.sun.com/products/plugin/downloads/index.html" title="Download Java plug-in">
Get the latest Java plug-in here
</a> (or enable Java support).
</p>
</object>
</div><!-- AppletContainer -->
<p>
Click on the button to format the table content to the locale rules of the user.
</p>
<input type="button" name="DoFormatting" id="DoFormatting" value="Format the table" onclick="javascript:DoFormatting()"/>
<div id="Results">
</div><!-- Results -->
<table class="toFormat">
<caption>Synthetic View</caption>
<thead><tr>
<th>Name</th><th>Value</th><th>Cost</th><th>Discount</th>
</tr></thead>
<tbody>
<tr><td>Foo</td><td class="number">3.1415926</td><td class="currency">21.36</td><td class="percent">0.196</td></tr>
<tr><td>Bar</td><td class="number">159263.14</td><td class="currency">33</td><td class="percent">0.33</td></tr>
<tr><td>Baz</td><td class="number">15926</td><td class="currency">12.99</td><td class="percent">0.05</td></tr>
<tr><td>Doh</td><td class="number">0.01415926</td><td class="currency">5.1</td><td class="percent">0.1</td></tr>
</tbody>
</table>
</div><!-- Container -->
</body>
</html>
Tested on Firefox 3.0, IE 6, Safari 3.1 and Opera 9.50, on Windows XP Pro SP3.
It works without problem with the first two, on Safari I have a strange error after init() call:
java.net.MalformedURLException: no protocol:
at java.net.URL.<init>(Unknown Source)
at java.net.URL.<init>(Unknown Source)
at java.net.URL.<init>(Unknown Source)
at sun.plugin.liveconnect.SecureInvocation.checkLiveConnectCaller(Unknown Source)
at sun.plugin.liveconnect.SecureInvocation.access$000(Unknown Source)
at sun.plugin.liveconnect.SecureInvocation$2.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at sun.plugin.liveconnect.SecureInvocation.CallMethod(Unknown Source)
but it still works.
I can't get it work with Opera: the applet loads correctly, as I can see the trace of init() call in the Java console, I have no errors when JavaScript calls the Java functions (except if I add and call a method getting a JSObject parameter, curiously), but the Java functions are not called (I added trace of the calls).
I believe Liveconnect works in Opera, but I don't see yet how. I will research a bit more.
[Update] I removed references to non-existing jar file (which doesn't stop other browsers) and I got a trace of the calls, but it doesn't update the page.
Mmm, if I do alert(applet.GetLocaleInformation()); I got the information, so it might be a jQuery issue.
Even if you knew what locale this "GUI Application" is running under, you still have to figure out how it is getting the current locale, and how it is determining the decimal separator.
i don't know how it is done on a Mac, but on Windows applications are supposed to interrogte the user's preferences set via the Control Panel. It's quite possible this mystery applicaiton is ignoring those settings, and using their own internal setup instead.
Or perhaps they're taking the current locale, and inferring the rest, rather than being told.
Even then, in english, numbers are given in groups of 3 digits, with a comma separating the groups. i.e.:
5,197,359,078
Unless the number was an integer that contains a phone number:
519-735-9078
Unless of course the number was an integer that contains an account number:
5197359078
In which case, you're back to hard-coded overridden logic.
Edit: Removed currency example, since currency has its own formatting rules.
"Is there any way to do it on server
side (preferably, so that I can
collect statistics), or on client
side?"
No you can't. That GUI is looking at some user or machine specific settings.
First, you probably do not know at what settings this UI is looking.
Second, with a webapplication you will probably not be able to check these settings (clientside --> Javacsript).
Is there any way to do it on server side (preferably, so that I can collect statistics), or on client side?
from Server side. That could get decimal separator from system by (.NET)
string x = CultureInfo.CurrentCulture.NumberFormat.NumberDsecimalSeparator;
The rest of work is check delimiter for exporting which is different from x
comma (",") or semicolon (";") in case csv export
Another possible solution: You could use something like GeoIP (example in PHP) to determine the user's location and decide based on these information.