PHP crop image - wrong area - image

On the clientside I have a jQuery script which I use to select a square area on the picture.
I got x1, y1 and width, height parameters. They are sent correctly to the server.
I want to crop image to this selection and then convert to PNG (although I tried both imagejpg, imagepng functions)
The code is (I use laravel 4):
$file = Input::file('picture');
$filename = md5(microtime()).'.png';
$image = imagecreatefromstring(file_get_contents($file->getRealPath()));
$crop = imagecreatetruecolor(Input::get('width'), Input::get('height'));
imagecopy($crop, $image, 0, 0, (int)Input::get('x1'), (int)Input::get('y1'), Input::get('width'), Input::get('height'));
imagepng($crop, public_path().'/uploads/pictures/'.$filename);
It works perfectly when height > width of original image. When I try to crop wide images (width > height) I got wrong area and it seems like x1,y1 are wrong (although they're not). I got right width/height, but wrong section.
What's wrong with the code above?

Solved. The problem was that client side didn't take into account original image size, it was scaled with CSS

Related

Solving Overlapping Images when zooming in Codenameone

I have an imageviewer with a couple images, When i zoom in the first image and wanna see the right side of the image. The folowing image is overlapping the inzooming image. This is very annoying. Is there a way how i can set the zoom in image on the front.
How can i set the zoomed image always on front.
See picture https://i.stack.imgur.com/5f5JZ.jpg
My imageviewer is in a container
Image red ;
red = EncodedImage.create("/HW_Delfzijl_Waddenzee_Oost.jpg");
Image blue = Image.createImage(500, 500, 0xff0000ff);
Image red2 = Image.createImage(500, 500, 0xffff0000);
Image List1[]= new Image [3];
List1[0] = red;
List1[1] = blue;
List1[2] = red2;
iv = new ImageViewer();
iv.setWidth(500);
iv.setHeight(500);
iv.setImageList(new DefaultListModel<>(List1));
Container1 = BoxLayout.encloseY( Kaarten.AuvHW, AdvSpr,iv,
Up,progressbar);
I was able to reproduce this with the following code:
Form hi = new Form("ImageViewer", BoxLayout.y());
Image red = Image.createImage(2000, 800, 0xffff0000);
Image blue = Image.createImage(2000, 500, 0xff0000ff);
ImageViewer viewer = new ImageViewer();
viewer.setImageList(new DefaultListModel<>(red, blue));
hi.add(BoxLayout.encloseY(viewer, new Label("Dummy")));
hi.show();
The problem only happens if I stand on the blue image (the second one) scale it up and then try to move. It doesn't happen when moving from the red image to the blue.
I believe this is due to this method in the ImagaViewer code. Since background isn't painted the old image isn't cleaned up. We need to add a condition that disables that while dragging. I think changing the code in that method to this will fix the problem but it's a bit risky and might trigger flickering:
protected void paintBackground(Graphics g) {
// disable background painting for performance when zooming
if(imageDrawWidth < getWidth() || imageDrawHeight < getHeight() || panPositionX != 0) {
super.paintBackground(g);
}
}
I would suggest filing an issue so we can consider the options here as this isn't trivial. One partial workaround is to use:
viewer.setImageInitialPosition(ImageViewer.IMAGE_FILL);
Which minimizes the impact of the issue.

PsychToolBox GetImage doesn't save using given rect dimensions

I'm trying to save a cropped portion of the screen from my PTB experiment, but the Screen('GetImage',...) function is not working properly. Here is my code:
screenNumber = 0;
% Open screen with grey background
[w, rect] = Screen('OpenWindow', screenNumber,...
background,[], [], [],[],6);
[xCenter, yCenter] = RectCenter(rect);
sideLength = randi([100 175], 1);
baseRect = [0, 0, sideLength, sideLength];
% Center the frame
centeredRect = CenterRectOnPoint(baseRect, xCenter, yCenter);
%dot position
dots.x = randi([ round(xCenter - (sideLength/2))+15 round(xCenter + (sideLength/2))-15], 1, numeral);
dots.y = randi([round(yCenter - (sideLength/2))+15 round(yCenter + (sideLength/2))-15], 1, numeral);
%skipping code to move dots.x into dot_info.position for brevity
Screen('DrawDots',w, dot_info.position, dot_info.size,...
dot_info.colour, [], 2); %dots are drawn to center of screen
Screen('Flip', w);
% Save dot cue
%im = Screen('GetImage', w);
im = Screen('GetImage', w, centeredRect);
imwrite(im, filename);
The issue is that there should be a small square image, centered on the centeredRect rectangle, which contains the dots I've drawn. However, all I get is a correctly sized rectangle without the dots. If I save without passing the centeredRect parameter (commented out line), I get a saved picture of the whole screen, showing the dots in the center - so I know the dots are being drawn. There must be something wrong with the GetImage call and its use of the rect, such that its not saving from the center point of the screen, so i just get the background. When I run this on my monitor it works fine, but on my laptop it does not. Unfortunately I don't have access to my monitor now so I need to get this to work on my laptop. I've checked with a Screens() call and there is only one screen: screen 0 - my laptop screen.
Any help greatly appreciated. Thanks.
SOLVED: I'm not sure why this worked, but I had to multiply the elements in centeredRect by 2. Hoping this helps someone else in future.

Print image to pdf without margin using Matlab

I'm trying to use the answers I found in these questions:
How to save a plot into a PDF file without a large margin around
Get rid of the white space around matlab figure's pdf output
External source
to print a matlab plot to pdf without having the white margins included.
However using this code:
function saveTightFigure( h, outfilename, orientation )
% SAVETIGHTFIGURE(H,OUTFILENAME) Saves figure H in file OUTFILENAME without
% the white space around it.
%
% by ``a grad student"
% http://tipstrickshowtos.blogspot.com/2010/08/how-to-get-rid-of-white-margin-in.html
% get the current axes
ax = get(h, 'CurrentAxes');
% make it tight
ti = get(ax,'TightInset');
set(ax,'Position',[ti(1) ti(2) 1-ti(3)-ti(1) 1-ti(4)-ti(2)]);
% adjust the papersize
set(ax,'units','centimeters');
pos = get(ax,'Position');
ti = get(ax,'TightInset');
set(h, 'PaperUnits','centimeters');
set(h, 'PaperSize', [pos(3)+ti(1)+ti(3) pos(4)+ti(2)+ti(4)]);
set(h, 'PaperPositionMode', 'manual');
set(h, 'PaperPosition',[0 0 pos(3)+ti(1)+ti(3) pos(4)+ti(2)+ti(4)]);
% save it
%saveas(h,outfilename);
if( orientation == 1)
orient portrait
else
orient landscape
end
print( '-dpdf', outfilename );
end
Results in this output:
As you can see the 'PaperSize' seems to be set not properly. Any idea of possible fixes?
NOTE
If I change the orientation between landscape and portrait the result is the same, simply the image is chopped in a different way.
However if I save the image with the saveas(h,outfilename); instruction the correct output is produced.
Why is this? And what is the difference between the two saving instructions?
Alltogether the answers you mentioned offer a lot of approaches, but most of them didn't worked for me neither. Most of them screw up your papersize when you want to get the tight inset, the only which worked for me was:
set(axes_handle,'LooseInset',get(axes_handle,'TightInset'));
I finally wrote a function, where I specify the exact height and width of the output figure on paper, and the margin I want (or just set it to zero). Be aware that you also need to pass the axis handle. Maybe this functions works for you also.
function saveFigure( fig_handle, axes_handle, name , height , width , margin)
set(axes_handle,'LooseInset',get(axes_handle,'TightInset'));
set(fig_handle, 'Units','centimeters','PaperUnits','centimeters')
% the last two parameters of 'Position' define the figure size
set(fig_handle,'Position',[-margin -margin width height],...
'PaperPosition',[0 0 width+margin height+margin],...
'PaperSize',[width+margin height+margin],...
'PaperPositionMode','auto',...
'InvertHardcopy', 'on',...
'Renderer','painters'... %recommended if there are no alphamaps
);
saveas(fig_handle,name,'pdf')
end
Edit: if you use painters as renderer saveas and print should produce similar results. For jpegs print is preferable as you can specify the resolution.

Magento resize() image quality: dirty white background

I have a client who is seriously unhappy with the way their product thumbnails are rendering on Magento.
The dodgy appearance is noticeable on two accounts:
there is a dirty white background which has very light grey horizontal lines
and secondly there is ever so slight color loss (loses contrast and saturation).
I have removed ALL compression, set ALL quality to 100%, flushed image cache, experimented, broken, and fixed it all dozens of times, and nothing seems to work.
This version of Magento is ver. 1.4.2.0
Is anyone out here experiencing the same problems, and if so have you managed to fix it?
The problem has to do with the php function imagecopyresampled in the resize function inside lib/Varien/Image/Adapter/Gd2.php, there are some rounding issues that occur to make a smoothly resized image.
My solution is to simply change any very light grey pixels in the image to pure white after the image has been resized. To do so first copy lib/Varien/Image/Adapter/Gd2.php to app/code/local/Varien/Image/Adapter/Gd2.php
Next find the following code inside the resize function (around line 312)
// resample source image and copy it into new frame
imagecopyresampled(
$newImage,
$this->_imageHandler,
$dstX, $dstY,
$srcX, $srcY,
$dstWidth, $dstHeight,
$this->_imageSrcWidth, $this->_imageSrcHeight
);
Then add the following code underneath:
// Clean noise on white background images
if ($isTrueColor) {
$colorWhite = imagecolorallocate($newImage,255,255,255);
$processHeight = $dstHeight+$dstY;
$processWidth = $dstWidth+$dstX;
//Travel y axis
for($y=$dstY; $y<($processHeight); ++$y){
// Travel x axis
for($x=$dstX; $x<($processWidth); ++$x){
// Change pixel color
$colorat=imagecolorat($newImage, $x, $y);
$r = ($colorat >> 16) & 0xFF;
$g = ($colorat >> 8) & 0xFF;
$b = $colorat & 0xFF;
if(($r==253 && $g == 253 && $b ==253) || ($r==254 && $g == 254 && $b ==254)) {
imagesetpixel($newImage, $x, $y, $colorWhite);
}
}
}
}
Flush the images cache from the Cache management in Magento, and you should have nicer images for the new displays. Few things to note when implementing this, there is a small performance hit the first time you generate the images again, and images with shadows may have sharper edges as the very light greys have been removed.
try following example
echo Mage::helper('catalog/image')->init($product, 'small_image')->resize(180, 210)->setQuality(50);
You can put your own Gd2.php file in local (app/code/local/Varien/Image/Adapter/Gd2.php) and hard-wire the quality to 100%.
Quality is working for me so I have not done that.
You can also put an image convolution in there to sharpen your images, in that way you get the blur of a resize compensated for with a sharpen, e.g. put the following just inside the end of the 'resize' function:
$sharpenMatrix = array(array(-1,-1,-1),array(-1,24,-1),array(-1,-1,-1));
$divisor = 16;
$offset = 0;
imageconvolution($newImage, $sharpenMatrix, $divisor, $offset);
I had problems with images quality on one of projects. But the problem was not on back-end, but on the front-end. Images had bad quality because images width and height given in the CSS was not the same as the image file had.
quick grep shows that you are able to set this on product_image object
app/code/core/Mage/Catalog/Helper/Image.php:105: * Set image quality, values in percentage from 0 to 100
app/code/core/Mage/Catalog/Helper/Image.php:107: * #param int $quality
app/code/core/Mage/Catalog/Helper/Image.php:110: public function setQuality($quality)
app/code/core/Mage/Catalog/Helper/Image.php:112: $this->_getModel()->setQuality($quality);
app/code/core/Mage/Catalog/Model/Product/Image.php:38: protected $_quality = 90;
app/code/core/Mage/Catalog/Model/Product/Image.php:88: * Set image quality, values in percentage from 0 to 100
app/code/core/Mage/Catalog/Model/Product/Image.php:90: * #param int $quality
app/code/core/Mage/Catalog/Model/Product/Image.php:93: public function setQuality($quality)
app/code/core/Mage/Catalog/Model/Product/Image.php:95: $this->_quality = $quality;
app/code/core/Mage/Catalog/Model/Product/Image.php:100: * Get image quality
app/code/core/Mage/Catalog/Model/Product/Image.php:106: return $this->_quality;
app/code/core/Mage/Catalog/Model/Product/Image.php:331: 'quality' . $this->_quality
app/code/core/Mage/Catalog/Model/Product/Image.php:387: $this->_processor->quality($this->_quality);
I had the same issue with some of my images, later i realized that those images with lower resolution were getting distorted, try using an image more than 1100 X 1100 and it should work just fine !
Upload the images as PNG's. They may not be as small as JPG, but it allowed us to avoid some image quality issues created by Magento's resizing functionality.

IF image is too big, how do I reduce the size?

My Website
On the above link you can see that the middle news post has an image that is just too big.
The info for the news is taken out of a database so I'm not sure how to change the width of the image on only certain images. Ideally I'd like to have any image that is over 300px wide to be kept at 300px. This is what I have so far:
echo '<img src="media/'.$row['media1'].'" class="floatLeftClear" id="border">';
I tired adding width="300" to the above statement but that made ALL of the images become 300px which I don't want. I only want images bigger than 300px to be reduced to 300.
Can someone point me in the right direction please!
If you don't want to physically resize the images on the server, which would be the ideal solution, you can set the max-width property via CSS.
img {
max-width:300px;
}
Note that the property is not supported in IE6 and below.
The code helps to resizing the image. its resize the height and width depends upon the max width
function fixImgs(whichId, maxW) {
var pix=document.getElementById(whichId).getElementsByTagName('img');
for (i=0; i<pix.length; i++) {
w=pix[i].width;
h=pix[i].height;
if (w > maxW) {
f=1-((w - maxW) / w);
pix[i].width=w * f;
pix[i].height=h * f;
}
}
}
fixImgs('photos', 108); // ('element ID', maximum width)
But one thing the image size(KB) is not reduce. I hope its help to you .
Why not to add a special routine for news images layout, define max-size within it and call it for the related images?

Resources