Canvas image produces awful color shifts in Chrome and Firefox (Mac) when saved to disk or uploaded to server. Safari has faithful color. Examples below + JSFiddle to reproduce with original image. Notice how the subject's face becomes very orange.
http://jsfiddle.net/E4yRv/141/
:: Includes step-by-step with sample images on how to reproduce
Code Excerpt:
canvas.ondrop = function(e) {
e.preventDefault();
var file = e.dataTransfer.files[0],
reader = new FileReader();
reader.onload = function(event) {
var img = new Image(),
imgStr = event.target.result,
imgData = context.getImageData(0,0, context.width,context.height);
state.innerHTML += ' Img source dropped in: <a href="' +
imgStr + '" target="_blank">save image</a><br />';
img.src = event.target.result;
img.onload = function(event) {
context.height = canvas.height = this.height;
context.width = canvas.width = this.width;
context.drawImage(this, 0, 0);
state.innerHTML += ' Canvas img drawn: save canvas <br />*add .jpg extension when saving';
};
};
reader.readAsDataURL(file);
return false;
};
When canvas draws the image in the respective browser the color renders to match the original. However, if the image is saved to disk locally and viewed in Photoshop (the only program that knows how to true handle color) the colors have shifted! Same occurs if viewing the saved file in a different browser.
Inspecting the images in photoshop, none have an embedded color profile. However, there is some translation of color that has occurred! It does not appear to be a case of misaligned profile or missing profile.
I have produced a detailed JS-Fiddle below on how to reproduce the issue.
http://jsfiddle.net/E4yRv/141/
I have encountered the similar color shift phenomenon in browser recently, and the translation of color in the human face can be reproduced by the JSFiddle code. After some research and thanks to the suggestion provided by Alexander O'Mara (the color profile in image), here is my conclusion:
The phenomenon should be caused by the embedded color profile in the sample image. If you open the original image in photoshop, it will show a warning window, which indicates that the color profile doesn't match the current used color gamut, and three options can be chosen:
use embedded color profile (in short, let's call it ref_ICC)
convert the color to the current used color gamut (after the conversion, a new ICC, i.e., the con_ICC, will be embedded in the resulting image)
ignore the color profile
After saving the three images by choosing the respective options, let's open them in some image viewer. I use XnView to check if any color profile (ICC) is embedded in image, and use Photoshop to check the RGB histogram. The result is:
(the downloaded* stands for the image obtained by the JSFiddle code of canvas.toDataURL)
| option 1 | option 2 | option 3 | downloaded*
histogram | ref_hist | con_hist | ref_hist | con_hist
ICC | ref_ICC | con_ICC | X | X
In a viewer (FastStone, for example) which doesn't care about the color profile (ICC), the displayed RGB value only depends on the histogram. So the original image (option 1) looks different from the downloaded one, in which the histogram seems to be converted by the browser in a way similar to the photoshop does for option 2. On the other hand, the image pairs of "option 1 & 3" and "option 2 & downloaded" show the same displayed value.
If the images are viewed in photoshop, then the three images (option 1 & 2 & downloaded) show the same displayed value. And as a final comparison, the displayed value of the downloaded image is the same in FastStone and Photoshop, while the original image shows different displayed value in these two viewers.
Related
I want to crop an image with Google App Script if an image outside the page frame, but as far as I checked in Google App Script documentation and I could not find a way to crop the image.
pageElements.asImage().replace (imgBlob, true); it is not allowed to pass cropping dimensions as parameters in .replace() to crop a image.
i know this can be achieved using a custom API , passing the image blob and crop area that will call cropping method on another server.
But how it will be possible to work with Google App Script, looking for expert advice.
How about this answer?
Issue:
I think that in the current stage, replace(blobSource, crop) has the limitation. The official document says as follows.
crop Boolean: If true, crops the image to fit the existing image's size. Otherwise, the image is scaled and centered.
I confirmed that when the image is cropped using replace(blobSource, crop), the center of image is left. It seems that this is the current specification. And although there is the "cropProperties" of "UpdateImagePropertiesRequest" in Slides API, unfortunately, in the current stage, this cannot be still used. This has already been reported. Ref
Sample script:
If you use replace(blobSource, crop) under the current specification, how about the following sample script? As the sample situation, 2 images of "image1" and "image2" are prepared in the 1st slide, and "image1" is cropped using "image2".
The flow of this script is as follows.
Flow:
Retrieve 2 images from a slide on Google Slides.
Crop "image1" using "image2". By this, "image2" is replaced with "image1".
Move the cropped image to "image1".
Remove the original "image1".
Script:
function myFunction() {
// 1. Retrieve 2 images from a slide on Google Slides.
var slide = SlidesApp.getActivePresentation().getSlides()[0];
var images = slide.getImages();
var image1 = images[0]; // Red image.
var image2 = images[1]; // Blue image.
// 2. Crop "image1" using "image2". By this, "image2" is replaced with "image1".
var replacedImage = image2.replace(image1.getBlob(), true);
// 3. Move the cropped image to "image1".
replacedImage.setTop(image1.getTop()).setLeft(image1.getLeft());
// 4. Remove the original "image1".
image1.remove();
}
Result:
When the script is run, "image1" is cropped. But it is found that in the current stage, the center of "image1" is left by the crop.
Note:
Slides API and Slides Service are growing now. So I think that this situation might be changed by the future update. But if you want this soon, how about requesting this to the issue tracker as the future request? Ref
References:
replace(blobSource, crop)
CropProperties
Added:
At an additional sample script for using replace(blobSource, crop), I would like to propose the method for using the self image. In this sample script, when the image is sticked out, the image of out of page is removed by cropping. The basic method is the same with above sample script.
Sample script:
function myFunction() {
var s = SlidesApp.getActivePresentation();
var slide = s.getSlides()[0];
var images = slide.getImages();
var image = images[0];
var pageWidth = s.getPageWidth();
var imagePosition = image.getLeft();
var imageWidth = image.getWidth();
var check = imagePosition + imageWidth - pageWidth;
if (check > 0 && check < imageWidth) {
image
.duplicate()
.setWidth(pageWidth - imagePosition)
.asImage()
.replace(image.getBlob(), true);
image.remove();
}
}
Result:
Note:
In this sample script, as a simple sample, I prepared only the right side of the horizontal direction. So when you want to remove the vertical direction, please modify the script for your actual situation.
In my UWP app we have images that users upload and they can be pretty much any size - so when I load these into in an Image control I resize them proportionally so they fit best into our image container (which is fixed at 112w x 152h) but as some images are wider than higher what I want to is find the background color of the image so I can set the Background of the image.
So to do this I am using the NuGet ColorThief package and the code below (taken from the sample I found there) is returning me the wrong dominant color in many cases:
var ct = new ColorThief();
QuantizedColor qc = await ct.GetColor(decoder); //BitmapDecoder containing image
Windows.UI.Color c = Windows.UI.Color.FromArgb(qc.Color.A, qc.Color.R, qc.Color.G, qc.Color.B);
setImageBackgroundColor(bgColour);
One image I tried it on was this one - now the dominant colour should clearly be black but it's returning some medium grey colour.... so is there something wrong with my code or my image or is there something else I need to do? I'm just not finding it reliable but I know others use it without issue.
According to the source code of the library, it seems it is actually averaging out the colors from the color palette of the picture
public async Task<QuantizedColor> GetColor(BitmapDecoder sourceImage, int quality = DefaultQuality,
bool ignoreWhite = DefaultIgnoreWhite)
{
var palette = await GetPalette(sourceImage, 3, quality, ignoreWhite);
var dominantColor = new QuantizedColor(new Color
{
A = Convert.ToByte(palette.Average(a => a.Color.A)),
R = Convert.ToByte(palette.Average(a => a.Color.R)),
G = Convert.ToByte(palette.Average(a => a.Color.G)),
B = Convert.ToByte(palette.Average(a => a.Color.B))
}, Convert.ToInt32(palette.Average(a => a.Population)));
return dominantColor;
}
In this particular case, I think setting ignoreWhite to true might return the actual black color, although it seems true is indeed the default setting.
I recommend using the other public method the library provides: GetPalette, to see what is the actual color palette of this image. This should explain why you are getting this particular color.
var palette = await GetPalette(decoder);
In my opinion you need to set quality from 5 to 10 and use GetPalette method with first color from palette.
QuantizedColor dominantColor = colorThief.GetPalette(tempBitmap, 5, 5, true)[0];
I'm using open source library for PDF documents from mozilla(pdf.JS).
When i'm trying to open pdf documents with bad quality, viewer displays it with VERY BAD quality.
But if I open it in reader, or in browser (drag/drop into new window), whis document displays well
Is it possible to change?
Here is this library on github mozilla pdf.js
You just have to change the scaling of your pdf i.e. when rendering a page:
pdfDoc.getPage(num).then(function(page) {
var viewport = page.getViewport(scale);
canvas.height = viewport.height;
canvas.width = viewport.width;
...
It is the scale value you have to change. Then, the resulting rendered image will fit into the canvas given its dimensions e.g. in CSS. What this means is that you produce a bigger image, fit it into the container you had before and so you effectively improve the resolution.
There is renderPage function in web/viewer.js and print resolution is hard-coded in there as 150 DPI.
function renderPage(activeServiceOnEntry, pdfDocument, pageNumber, size) {
var scratchCanvas = activeService.scratchCanvas;
var PRINT_RESOLUTION = 150;
var PRINT_UNITS = PRINT_RESOLUTION / 72.0;
To change print resolution to 300 DPI, simply change the line below.
var PRINT_RESOLUTION = 300;
See How to increase print quality of PDF file with PDF.js viewer for more details.
Maybe it's an issue related with pixel ratio, it used to happen to me when device pixel ratio is bigger than 1 (for example iPhone, iPad, etc.. you can read this question for a better explanation.
Just try that file on PDF.js Viewer. If it works like expected, you must check how PDF.js works with pixel ratio > 1 here. What library basically does is:
canvas.width = viewport.width * window.devicePixelRatio;
canvas.styles.width = viewport.width + 'px'; // Note: The px unit is required here
But you must check how PDF.js works for better perfomance
I ran into the same issue and I used the intent option of renderContent to fix that.
const renderContext = {
intent: 'print',
// ....
}
var renderTask = page.render(renderContext);
As per docs renderContext accepts intent which supports three values - display, print or any. The default is display. When I used print instead the render quality was extremely good, at par with any desktop app.
I am looking to make a photoshop action (maybe this isn't possible, any other application recommendations would be helpful as well). I want to take a collection of photos and make them a certain aspect ration, ex: 4:3.
So I have an image that is 150px wide by 200px high. What I would like to happen is the image's canvas is made to be 267px wide, with the new area filled with a certain color.
So there are two possibilities I can think of:
1) Photoshop actions could do this, but I would have to pull current height, multiply by 1.333333 and then put that value in the width box of the canvas resize. Is it possible to have calculated values in Photoshop actions?
2) Some other application has this feature built in.
Any help is greatly appreciated.
Wow, I see now (after writing the answer) that this was asked a long time ago. . . oh well. This script does the trick.
This Photoshop script will resize any image's canvas so that it has a 4:5 aspect ratio. You can change the aspect ratio applied by changing arWidth and arHeight. The fill color will be set to the current background color. You could create an action to open a file, apply this script, then close the file to do a batch process.
Shutdown Photoshop.
Copy this javascript into a new file named "Resize Canvas.jsx" in Photoshop's Presets\Scripts folder.
Start Photoshop and in the File - Scripts menu it should appear.
#target photoshop
main ();
function main ()
{
if (app.documents.length < 1)
{
alert ("No document open to resize.");
return;
}
// These can be changed to create images with different aspect ratios.
var arHeight = 4;
var arWidth = 5;
// Apply the resize to Photoshop's active (selected) document.
var doc = app.activeDocument;
// Get the image size in pixels.
var pixelWidth = new UnitValue (doc.width, doc.width.type);
var pixelHeight = new UnitValue (doc.height, doc.height.type);
pixelWidth.convert ('px');
pixelHeight.convert ('px');
// Determine the target aspect ratio and the current aspect ratio of the image.
var targetAr = arWidth / arHeight;
var sourceAr = pixelWidth / pixelHeight;
// Start by setting the current dimensions.
var resizedWidth = pixelWidth;
var resizedHeight = pixelHeight;
// The source image aspect ratio determines which dimension, if any, needs to be changed.
if (sourceAr < targetAr)
resizedWidth = (arWidth * pixelHeight) / arHeight;
else
resizedHeight = (arHeight * pixelWidth) / arWidth;
// Apply the change to the image.
doc.resizeCanvas (resizedWidth, resizedHeight, AnchorPosition.MIDDLECENTER);
}
Mind that the accepted answer from #user268911 may not work for you if the source image has different pixels/inch than 72. Because the UnitValue.convert function works correctly only with 72 px/inch. To be sure the conversion is correct for ever pixel/inch value, set baseUnit property as follows:
...
var pixelWidth = new UnitValue (doc.width, doc.width.type);
pixelWidth.baseUnit = UnitValue (doc.width.baseUnit, "in");
var pixelHeight = new UnitValue (doc.height, doc.height.type);
pixelHeight.baseUnit = UnitValue (doc.height.baseUnit, "in");
...
For more details about the conversion see "Converting pixel and percentage values" section of the Adobe JavaScript Tools Guide.
What languages do you know? ImageMagick has command line tools that can do this, but you'd need to know a scripting language to get the values and calculate the new ones.
For .NET, my company's product, DotImage Photo, is free and can do this (need to know C# or VB.NET)
I'm using Codeigniter's image manipulation library to re-size an uploaded image to three sizes, small, normal and large.
The re-sizing is working great. However, if I'm resizing a vertical image, the library is rotating the image so it's horizontal.
These are the config settings I have in place:
$this->resize_config['image_library'] = 'gd2';
$this->resize_config['source_image'] = $this->file_data['full_path'];
$this->resize_config['maintain_ratio'] = TRUE;
// These change based on the type (small, normal, large)
$this->resize_config['new_image'] = './uploads/large/'.$this->new_file_name.'.jpg';
$this->resize_config['width'] = 432;
$this->resize_config['height'] = 288;
I'm not setting the master_dim property because the default it set to auto, which is what I want.
My assumption is that the library would take a vertical image, see that the height is greater than the width and translate the height/width config appropriately so the image remains vertical.
What is happening (apparently) is that the library is rotating the image when it is vertical and sizing it per the configuration.
This is the code in place I have to do the actual re-sizing:
log_message('debug', 'attempting '.$size.' photo resize');
$this->CI->load->library('image_lib');
$this->CI->image_lib->initialize($this->resize_config);
if ($this->CI->image_lib->resize())
{
$return_value = TRUE;
log_message('debug', $size.' photo resize successful');
}
else
{
$this->errors[] = $this->CI->image_lib->display_errors();
log_message('debug', $size.' photo resize failed');
}
$this->CI->image_lib->clear();
return $return_value;
EDIT
I think the problem may be from the upload library. When I get the image_height and image_width back from the upload, the width seems to be larger even though I uploaded a vertical image.
This is a portion of the code I'm using to upload the photo:
$this->upload_config['allowed_types'] = 'jpg|jpeg';
$this->upload_config['max_size'] = '2000';
$this->upload_config['max_width'] = '0';
$this->upload_config['max_height'] = '0';
$this->upload_config['upload_path'] = './uploads/working/';
$this->CI->load->library('upload', $this->upload_config);
if ($this->CI->upload->do_upload($this->posted_file))
{
$this->file_data = $this->CI->upload->data();
$return_value = TRUE;
log_message('debug', 'upload successful');
}
I added some logging to check the values:
$this->is_vertical = $this->file_data['image_height'] > $this->file_data['image_width'];
log_message('debug', 'image height:'.$this->file_data['image_height']);
log_message('debug', 'image width:'.$this->file_data['image_width']);
if ($this->is_vertical)
{
$this->resize_config['master_dim'] = 'height';
}
else
{
$this->resize_config['master_dim'] = 'width';
}
log_message('debug', 'master_dim setting:'.$this->resize_config['master_dim']);
These are the results of the log:
DEBUG - 2010-03-16 18:35:06 --> image height:1536
DEBUG - 2010-03-16 18:35:06 --> image width:2048
DEBUG - 2010-03-16 18:35:06 --> master_dim setting:width
Looking at the image in photoshop, these are the dimensions:
height: 2048
width: 1536
Anyone know what might be causing the upload library to do this?
I've never used this library, but having read the documentation, I wonder whether the master_dim property might help. If you set this to 'height' for vertical images that might keep them the right way up. You could just parse each image through a conditional to see if the image is vertically aligned and then only set this property if need be.
My other thought is about the maintain_ratio property. The documentation says that with this set to 'TRUE' it will resize as close to the target values as possible whilst maintaining the aspect ratio. I wonder if it thinks that rotating the image allows it to preserve this ratio more accurately? As an experiment, try setting this value to 'FALSE' for vertical images.
Ok - I decided not to trust photoshop and opened the images I was testing in quicktime and safari. I discovered that they were actually still horizontal.
So Codeigniter was operating exactly as expected.
I went back into photoshop, did a save for web on the test images, re-uploaded them and it worked as expected.
I then stripped out the extra code that I had added to test whether the image was vertical and the library works as I expected it would.
Now - I need to figure out how to prevent end users from doing this exact thing.
Thanks for taking the time to answer my question musoNic80. Hopefully someone else can learn from my mistakes here.