read pixels from image and randomly show single pixels in browser with PHP - pixel

I have an image that is saved in a database. I need a script that can read the RGB + x and y value of each pixel of this image.
This is needed because I want to be able to show random pixels of this image in a browser. With random I mean, random positions. The number of pixels is selected with a form. When the form is used, a number of pixels of the image will be visible in the browser and this new image will be saved. The next time the form is used, the new image with a few pixels visible, will be displayed in the browser. And so on.... each time the form is used, the image will get more and more visible.
I did some testing with the PHP GD library, but not been able to extract the RGB as well as the position of each pixel. For outputting an array of RGBA vallues, I used this how to count number of pixels in image (php). But as you see, this is just the beginning.
$img = "images/test.png";
$imgHand = imagecreatefrompng("$img");
$imgSize = GetImageSize($img);
$imgWidth = $imgSize[0];
$imgHeight = $imgSize[1];
// Define a new array to store the info
$pxlCorArr= array();
for ($l = 0; $l < $imgHeight; $l++) {
// Start a new "row" in the array for each row of the image.
$pxlCorArr[$l] = array();
for ($c = 0; $c < $imgWidth; $c++) {
$pxlCor = ImageColorAt($imgHand,$c,$l);
// Put each pixel's info in the array
$pxlCorArr[$l][$c] = ImageColorsForIndex($imgHand, $pxlCor);
}
}

do you want a partial image to be shown and then full image ? or random part of it ?
take a look at this ,
https://github.com/ogres/Image2HTML
it will convert an image to html table , you could edit it so only random part of image will be shown

Related

Making a long image without resizing

I need to put many images together side by side but without changing the height or width of any of them. That is to say, it will just be one image of a constant height but very long width as the image are sitting horizontally.
I've been using Python and the PIL library but what I've tried so far is producing an image that makes all the images smaller to concatenate into one long image.
Image.MAX_IMAGE_PIXELS = 100000000 # For PIL Image error when handling very large images
imgs = [ Image.open(i) for i in list_of_images ]
widths, heights = zip(*(i.size for i in imgs))
total_width = sum(widths)
max_height = max(heights)
new_im = Image.new('RGB', (total_width, max_height))
# Place first image
new_im.paste(imgs[0],(0,0))
# Iteratively append images in list horizontally
hoffset=0
for i in range(1,len(imgs),1):
hoffset=imgs[i-1].size[0]+hoffset # update offset**
new_im.paste(imgs[i],(hoffset,0))
new_im.save('row.jpg')
The result I'm getting now is one image made up of concatenated images in a horizontal row. This is what I want, except the images are being made smaller and smaller in the concatenation process. I want the end result to not make the images smaller and instead produce an image made of the input images with their original size. So the output image will just have to have a very long width.
It seems you have a bug while updating the offsets.
You should replace your iteration block with:
imgs = [Image.open(i) for i in list_of_images]
widths, heights = zip(*(i.size for i in imgs))
new_img = Image.new('RGB', (sum(widths), max(heights)))
h_offset = 0
for i, img in enumerate(imgs):
new_img.paste(img, (h_offset, 0))
h_offset += img.size[0]

How to store small images in MATLAB

I am attempting to convert a 1x8 array into an image, I know that the resulting image would be tiny. I do that using the following code:
filename = fullfile('/Users/jlmontalvo/Documents/MATLAB/train_data.csv');
T = readtable(filename);
C1 = [];
t = T(1,:);
a = t.Variables;
a(end) = []; %getting rid of the last value
test = getimage(imshow(a, [])); %display image
imwrite(test,'/Users/jlmontalvo/Desktop/hello.png'); %store image
the issue is that the image that MATLAB displays looks like this:
but the one that is actually saved is completely different and looks like this:
Why is this?
getimage gets the data displayed. That is, after
test = getimage(imshow(a, []));
test is identical to a.
You are showing the image with contrast stretch, making the smallest value black and the largest value white. But retrieving the data from those axes does not take any of that into account, it simply returns the displayed data.
Instead, you could stretch the data yourself:
test = double(a);
test = test - min(test(:));
test = test / max(test(:));

image stack display in matlab using a slider

I have a 3 dimension matrix of data (a stack of images across a dimension, time for example.
I want to display an image, and have a slider below to navigate across the images.
I wrote a piece of code which works, but it's bulky and kinda ugly I think...I want to write a clean function and so I would like to know if anyone know of a cleaner, nicer way to do it.
Here is my code:
interv = [min max]; % interval for image visualization
imagesc(Temps_visu,X*100,squeeze(X,Y,MyMatrix(:,:,1)),interv);
title('My Title');
xlabel('X (cm)');
ylabel('Y (cm)');
pos = get(gca,'position');
% slider position
Newpos = [pos(1) pos(2)-0.1 pos(3) 0.05];
pp = 1;
% callback slider
S = ['pp=floor(get(gcbo,''value''));imagesc(Temps_visu,X*100,squeeze(X,Y,MyMatrix(:,:,1)),interv));' ...
'set_axes_elasto;title(''My Title'');disp(pp);'];
Mz = size(MyMatrix,3);
% Creating Uicontrol
h = uicontrol('style','slider',...
'units','normalized',...
'position',Newpos,...
'callback',S,...
'min',1,'max',Mz,...
'value',pp,...
'sliderstep',[1/(Mz-1) 10/(Mz-1)]);
Here is a way to do it using a listener object for smooth visualization of your stack. I made up a dummy stack using grayscale variations of the same image (i.e. only 4 frames) but the principle will be the same for your application. Notice that I use imshow to display the images, but using imagesc as you do won't cause any problem.
The code is commented so hopefully this is clear enough. If not please don't hesitate to ask for help!
Code:
function SliderDemo
clc
clear all
NumFrames = 4; %// Check below for dummy 4D matrix/image sequence
hFig = figure('Position',[100 100 500 500],'Units','normalized');
handles.axes1 = axes('Units','normalized','Position',[.2 .2 .6 .6]);
%// Create slider and listener object for smooth visualization
handles.SliderFrame = uicontrol('Style','slider','Position',[60 20 400 50],'Min',1,'Max',NumFrames,'Value',1,'SliderStep',[1/NumFrames 2/NumFrames],'Callback',#XSliderCallback);
handles.SliderxListener = addlistener(handles.SliderFrame,'Value','PostSet',#(s,e) XListenerCallBack);
handles.Text1 = uicontrol('Style','Text','Position',[180 420 60 30],'String','Current frame');
handles.Edit1 = uicontrol('Style','Edit','Position',[250 420 100 30],'String','1');
%// Create dummy image sequence, here 4D sequence of grayscale images.
MyImage = imread('peppers.png');
MyMatrix = cat(4,rgb2gray(MyImage),MyImage(:,:,1),MyImage(:,:,2),MyImage(:,:,3));
%// Use setappdata to store the image stack and in callbacks, use getappdata to retrieve it and use it. Check the docs for the calling syntax.
setappdata(hFig,'MyMatrix',MyMatrix); %// You could use %//setappdata(0,'MyMatrix',MyMatrix) to store in the base workspace.
%// Display 1st frame
imshow(MyMatrix(:,:,:,1))
%// IMPORTANT. Update handles structure.
guidata(hFig,handles);
%// Listener callback, executed when you drag the slider.
function XListenerCallBack
%// Retrieve handles structure. Used to let MATLAB recognize the
%// edit box, slider and all UI components.
handles = guidata(gcf);
%// Here retrieve MyMatrix using getappdata.
MyMatrix = getappdata(hFig,'MyMatrix');
%// Get current frame
CurrentFrame = round((get(handles.SliderFrame,'Value')));
set(handles.Edit1,'String',num2str(CurrentFrame));
%// Display appropriate frame.
imshow(MyMatrix(:,:,:,CurrentFrame),'Parent',handles.axes1);
guidata(hFig,handles);
end
%// Slider callback; executed when the slider is release or you press
%// the arrows.
function XSliderCallback(~,~)
handles = guidata(gcf);
%// Here retrieve MyMatrix using getappdata.
MyMatrix = getappdata(hFig,'MyMatrix');
CurrentFrame = round((get(handles.SliderFrame,'Value')));
set(handles.Edit1,'String',num2str(CurrentFrame));
imshow(MyMatrix(:,:,:,CurrentFrame),'Parent',handles.axes1);
guidata(hFig,handles);
end
end
The figure looks like this:
Hope that helps!

Reassembling a fragmented image

I have an image that has been broken in to parts, 64 rows by 64 columns. Each image is 256x256px. The images are all PNG. They are named "Image--.png" for example "Image-3-57". The rows and columns numbering start from 0 rather than 1.
How can I assemble this back in to one image? Ideally using BASH and tools (I'm a sysadmin) though PHP would be acceptable as well.
Well, it is not very complicated, if you want to use PHP. What you need is just a few image gunctions - imagecreate and imagecopy. If your PNG is semi transparent, you will also need imagefilledrectangle to create a transparent background.
In code below, I rely on fact, that all chunks are same size - so the pixel size must be able to be divided by the number of chunks.
<?php
$width = 256*64; //height of the big image, pixels
$height = 256*64;
$chunks_X = 64; //Number of chunks
$chunks_Y = 64; //Same for Y
$chuk_size_X = $width/$chunks_X; //Compute size of one chunk, will be needed in copying
$chuk_size_Y = $height/$chunks_Y;
$big = imagecreate($width, $height); //Create the big one
for($y=0; $y<$chunks_Y; $y++) {
for($x=0; $x<chunks_X; $x++) {
$chunk = imagecreatefrompng("Image-$x-$y.png");
imagecopy($big, $chunk,
$x*$chuk_size_X, //position where to place little image
$y*$chuk_size_Y,
0, //where to copy from on little image
0,
$chuk_size_X, //size of the copyed area - whole little image here
$chuk_size_Y,
);
imagedestroy($chunk); //Don't forget to clear memory
}
}
?>
This is just a draft. I'm not sure about all theese xs and ys as well as ather details. It is late and I'm tired.

How can I add an image to a PDF at specific x-y coordinates using IText?

I have existing PDFs to which I need to dynamically add an image/images. The image comes from a file upload. Once I have the file uploaded, how can specify where to place the image on the PDF. One code snippet I found does not work correctly. This needs to work for PDFs with any number of pages. From what I understand, absolute positioning is set from the bottom-left corner of the last page of the PDF. If I need an image to be displayed 30 pixels from the top and 50 pixels from the left of page 1, how can I accomplish this? Or, if I need to display an image 50px from the top/100 px from the left on page 2?
I've tried using the code found at http://rip747.wordpress.com/2009/03/26/add-an-image-dynamically-to-a-pdf-with-cf-and-itext/. I've modified it for my needs below:
<cfscript>
myLeft = 30;
myTop = 50;
myPageNum = 1;
// output buffer to write PDF
fileIO = createObject("java","java.io.FileOutputStream").init(myOutputPath);
// reader to read our PDF
reader = createObject("java","com.lowagie.text.pdf.PdfReader").init(mySourcePath);
// stamper so we can modify our existing PDF
stamper = createObject("java","com.lowagie.text.pdf.PdfStamper").init(reader, fileIO);
// get the content of our existing PDF
content = stamper.getOverContent(reader.getNumberOfPages());
// create an image object so we can add our dynamic image to our PDF
image = createobject("java", "com.lowagie.text.Image");
// initalize our image
img = image.getInstance(imgPath);
x = (reader.getPageSize(1).width() - img.scaledWidth()) - myLeft;
y = (reader.getPageSize(1).height() - img.scaledHeight()) - myTop;
// now we assign the position to our image
img.setAbsolutePosition(javacast("float", x), javacast("float", y));
// add our image to the existing PDF
content.addImage(img);
// flattern our form so our values show
stamper.setFormFlattening(true);
// close the stamper and output our new PDF
stamper.close();
// close the reader
reader.close();
</cfscript>
The above code places my image at the top-right corner of page 2 - 50px form the top/30px from the left.
I know I'm close...just need a little help getting this nailed down for my needs.
I've updated my code. This gets the image to the top left corner of page 2 - correct positioning, but I want it on page 1:
x = myLeft;
y = (reader.getPageSize(1).height()) - img.scaledHeight() - myTop;
I thought maybe I needed to add the height of page 1 to get the image up to page 1, but the image completely disappears when I try either of the options below:
// I figure I'll need something like this to handle multi-page docs
y = (reader.getPageSize(1).height() * reader.getNumberOfPages()) - img.scaledHeight() - myTop;
y = reader.getPageSize(1).height() + reader.getPageSize(1).height() - img.scaledHeight() - myTop;
You're getting your "OverContent" from stamper.getOverContent(reader.getNumberOfPages());. The parameter for getOverContent() is the page number. So your code is getting a PdfContentByte for the last page, not the first.
I found my answer:
The page number has to be set in com.lowagie.text.pdf.PdfStamper.getOverContent():
content = stamper.getOverContent(myPageNum);
Knew it was easy.
are you using CF8+? You can use
<cfpdf action="addWatermark" source="myPDF.pdf" image="myImage.jpg"
position="0,0" rotation="0" showOnPrint="true" opacity="10">

Resources