PHP--Image Copy Resize won't save reduced photo - php

My jpg is 4kb, but when I upload it to the server, the PHP program writes it much larger, as 43kb, it's large and fuzzy, instead of being small and clear. How can I maintain the width and height? I've tried resizing after the photo is saved, but nothing happens. This is the code for the upload, and save.
<?php
// retrieve
echo "Request received";
$p= $_FILES["file"];
move_uploaded_file($p["tmp_name"], "pic3-1.jpg");
if ($p==nil) { echo "no photo"; }
// reply
$data = Array("Reply"=>"Imaged saved at server");
echo json_encode($data);
?>

Added to Xcode 8, Swift 3. The resolution is clear:
UIGraphicsBeginImageContext(CGSize(width:75, height: 75))
photo2.draw(in: CGRect(x: 0, y: 0, width: 75, height: 75))
photo=UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

Related

Wordpress thumbnail cropping not working

I've added the following code to my theme's functions.php file:
function add_custom_sizes() {
add_image_size('featured-thumbnail', 690, 500, true);
add_image_size('secondary-thumbnail', 460, 236, true);
add_image_size('related-thumbnail', 360, 262, true);
add_image_size('true-thumbnail', 337, 209, true);
add_image_size('search-thumbnail', 208, 130, true);
}
add_action('after_setup_theme', add_custom_sizes);
Within my template I have code such as:
<?php
if (has_post_thumbnail() ) {
the_post_thumbnail('featured-thumbnail');
} else { ?>
<img src="http://via.placeholder.com/690x500" alt="">
<?php } ?>
And this is the image it outputs:
<img width="690" height="407" src="https://s3.amazonaws.com/.../image-2440x1440.jpg" class="attachment-featured-thumbnail size-featured-thumbnail wp-post-image" alt="" />
The original size of the image is 2440px x 1440px so I don't understand why it's not respecting my height category. It's a brand new image that's been uploaded, but just to double check I've regenerated my thumbnails but the problem persists. I'm at a complete loss. I literally just banged my head against my desk.
Because it's preserving your aspect ratio
2440 / 1440 = 1.694
690 / 407 = 1.695

Image is not shown on php when I call mysql blob

I'm trying to get an image loaded on a mysql database as a blob. When I try to load, it just appear a black screen with a square in the middle. Like the image I attach.
please your help
PHP (file who show the image)
<?php
header("Content-type: image/jpeg");
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
require_once('sql.php');
require_once('encriptor.php');
$usrId = $_SESSION['usr-id'];
$sec= new encryptor();
$usrId = $sec->decrypt($usrId);
$db = new sql();
$consulta="CALL sp_getUserProfileImage(".$usrId.")";
$img="";
foreach($db->retorna($consulta) as $a)
{
$img=$a->picture;
}
echo $img;
?>
this is the line where I call the image:
<img src="masterlib/php/image_show.php" class="img-circle" alt="User Image">
Image error
please your help, thanks a lot!
Image in website need to have a directory like c:\images\sample.jpeg
You can't do it by fetching a blob from DB and assign the blob to an image control
Moving forward:
Save your image first then get the image file from your directory.

php Preventing dynamically added vertical images from being displayed horizontal

I have this problem with a simple cms I'm working on:
I have a simple php function getting image elements from a specified directory, and printing them to the html
<?php if($row["imgs"] == TRUE){ ?>
<div class="imrow">
<?php
$dir = $row["folder"];
$img = glob($dir."*.{jpg,jpeg,png}", GLOB_BRACE);
$tabing = 3;
$scale = sizeof($img);
for ($i = 0; $i < $tabing; $i++) {
echo '<img src="'.$img[$i].'" alt="image" />';
}
?>
</div><?php }//closing the first if of images ?>
(...)
<?php if($row["imgs"] == TRUE) { ?>
<div class="imrow">
<?php
for ($i = $tabing; $i < $scale; $i++) {
if(!($i % $tabing) && ($i!=0)){echo '</div><div class="imrow">';}
echo '<img src="'.$img[$i].'" alt="image" />';
}
?>
</div>
<?php }//second if closing ?>
The style for images and rows:
.imrow {
display: block;
}
.imrow img {
z-index: 10;
float: left;
height: 100%;
cursor: pointer;
transition: transform .5s ease;
box-shadow: 1px 1px 12px rgb(200, 200, 200);
}
And are laid out using a simple jQuery function
$(".imrow").each(function () { // for every row
var row = $(this); //it gives it a name
var rowW = row.width(); //it seals it's width
var imgW = 0; //it sets a image width variable
var fixH = 600; //and get a fixed amount
row.children().each(function () {
$(this).css("height", fixH); //apply fixed height to element in order to get ratio
imgW += $(this).width(); //get the width of this and
$(this).css("height", "100%");
arr.push($(this).attr("src")); // restore
});
row.css("height", rowW / (imgW / fixH) - 2);
});
The problem here is the fact that some of the added Vertical images, turn out horizontal
Here's how it looks in a folder
And how it turns out in the website:
EDIT: This is a php only issue from what I see, because when I analyze the elements in chrome, the images are flipped by default inside, as you all can see here:
So my first bet goes on glob doing something wrong.
Has anyone experienced it, or knows a way to make glob get everything properly?
Bare in mind that this issue only happens to some of the images, and is not depended on the format of the displayed image.
Any help would be extremely useful
It appears the problem was metadata stored in the images that describe the correct orientation.
There is a image-orientation css property that is supposed to be used to display the image in the correct orientation, but it doesn't seem to be supported in all browsers.
The only other solution at the moment is to edit the image's metadata with a metadata editor or, as you have, to open the images in photoshop and save them.

Why can't my php generated word document be opened?

In my xampp htdocs folder I got two files: An image and a php script. I tried to create a word document with an image. This is the code I used:
$image = 'img.png';
$imageData = base64_encode(file_get_contents($image));
$src = 'data: '. mime_content_type($image).';base64,'.$imageData;
header("Content-type: application/vnd.ms-word");
header("Content-Disposition: attachment;Filename=document_name.doc");
echo "<html>";
echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=Windows-1252\">";
echo "<body>";
echo "<h1>bla</h1>";
echo "<b>My first document</b>";
echo '<img src="',$src,'">';
echo "</body>";
echo "</html>";
Well actually I don't have Microsoft Word installed on my PC but it should work with Libre Office too. I also tried http://www.viewdocsonline.com but it didn't work. First I tried it with a way too big image and I thought that was causing the problem but it doesn't even work with a small image. The File is just loading all the time but can't be opened. The file size seems to be right - it's 52kb - so the image seems to be in the document.
But what could cause the error? How to find out and how to debug?
Word can't read Html, at least not if you specify the .doc extension.
You should use a Docx generator if you want to work with the latest version of Word (since 2007), or doc if you want to create a document readable from word 2003.
http://www.phpdocx.com/ works great for that (https://phpword.codeplex.com/ too, but isn't well supported)
Alright – with the help of edi9999 and his awesome library I was able to create a docx document with my text variables and my image.
Here is the code I used:
Javascript:
/*** importing all necessary scripts ***/
<script type="text/javascript" src="docxtemplater-master/libs/base64.js"></script>
<script type="text/javascript" src="docxtemplater-master/libs/jszip/jszip.js"></script>
<script type="text/javascript" src="docxtemplater-master/libs/jszip/jszip-load.js"></script>
<script type="text/javascript" src="docxtemplater-master/libs/jszip/jszip-inflate.js"></script>
<script type="text/javascript" src="docxtemplater-master/js/docxgen.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
/*** my JSON object with the variables for setTemplateVars() ***/
<script type="text/javascript">
var JSON = { "articles": [
{ "title": "test-title", "first_name": "Paul", "last_name": "Alan", "phone": "555-nose", "fileName": "abc" },
{ "title": "test-title2", "first_name": "John", "last_name": "Doe", "phone": "555-abcd", "fileName": "bcd" }
]
};
</script>
<script type="text/javascript">
var xhrDoc = new XMLHttpRequest();
xhrDoc.open('GET', 'Example.docx', true);
if (xhrDoc.overrideMimeType) {
xhrDoc.overrideMimeType('text/plain; charset=x-user-defined');
}
xhrDoc.onreadystatechange = function (e) {
if (this.readyState == 4 && this.status == 200) {
window.docData = this.response;
}
};
xhrDoc.send();
var xhrImage = new XMLHttpRequest();
xhrImage.open('GET', 'dog.jpg', true);
if (xhrImage.overrideMimeType) {
xhrImage.overrideMimeType('text/plain; charset=x-user-defined');
}
xhrImage.onreadystatechange = function (e) {
if (this.readyState == 4 && this.status == 200) {
window.imgData = this.response;
}
};
xhrImage.send();
generateDoc = function (docData) {
var doc = new DocxGen(docData)
doc.setTemplateVars(
{ "first_name": JSON.articles[0]["first_name"],
"last_name": JSON.articles[0]["last_name"],
"phone": JSON.articles[0]["phone"],
"fileName": JSON.articles[0]["fileName"]
}
)
doc.applyTemplateVars()
imageList = doc.getImageList()
console.log(imageList);
doc.setImage(imageList[0].path, imgData);
doc.output()
}
</script>
HTML:
<button class="download_doc" onClick="generateDoc(window.docData)">download word docx with image</button>
Word template:
{phone}
Product name: {first_name}
Product reference : {last_name}
*in the middle is an image*
Blabla: {fileName}
*here is another image*
Well the content makes no sense of course but it works. But still there are some questions left (especially to edi9999 and I hope you could answer them for me please :) ):
1. The images has to be on the same server and you have to use a relative path, right? Link's didn't seem to work. I tried xhrImage.open('GET', 'http://link-to-an-image.com/image.jpg', true); but without success. Is it somehow possible to use external links to images?
2. There is an 304 error ("Not modified") in the console behind the GET Requests. Is that normal?
3. Does the image that shall replace the image in the word document have to be the same size (or at least the same aspect ratio) or are there any option variables that could make the replacement more flexible? For example: if I wanna have the image displayed over the full width in the word document and got a replacement image with a different aspect ratio, would it be possible to keep that aspect ratio and just increase the height of the image in the word document?
4. How to use more than one image for replacement? With xhrImage.open('GET', 'dog.jpg', true); only one image is opened. How to add more images to the "imageList" and how to determine the order?
5. The library is based on prototype and normally it's causing errors to use both (jQuery + Prototype) frameworks in one document. But I tried to use a jQuery function and it worked. Have you ever had any problems with using your library and jQuery in one document?
Found another solution:
With this library: https://github.com/PHPOffice/PHPWord
it's quite easy to create a docx file with formatted text and an image.
Here's the code that worked for me:
require_once('PHPWord-master/Classes/PHPWord.php');
$PHPWord = new PHPWord();
$section = $PHPWord->createSection();
$my_text='Hello world! I am formatted.';
$section->addText($my_text, array('name'=>'Tahoma', 'size'=>16, 'bold'=>true));
$section->addText(''); // adding some white space because the marginTop attribute of the image doesn't work
$filename="Jellyfish.jpg";
$size = getimagesize($filename);
$width="560"; //full width in a word document if image is 96dpi
$height=560/intval($size[0])*intval($size[1]);
$section->addImage(
$filename,
array(
'width' => $width,
'height' => $height,
'align' => 'center'
)
);
$section->addText('blabla');
$filename="dog.jpg";
$size = getimagesize($filename);
$height=560/intval($size[0])*intval($size[1]);
$section->addImage(
$filename,
array(
'width' => $width,
'height' => $height,
'align' => 'center'
)
);
$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
$objWriter->save('helloWorld.docx');

session in php image

I am working on a form which is validated with jQuery before being submitted. One of the fields is a captcha.
The idea is very simple, the captcha is shown as an image and also stored in a hidden field. When the user enters the captcha in the input field it should be equal to the value of the hidden field. This is the jQuery code I have;
<script>
$(document).ready(function(){
$("#register").validate({
errorElement: 'div', ignore: 'hidden',
rules: {
password: {
required: true
},
password2: {
required: true, equalTo: "#password"
},
agree: {
required: true
},
captcha: {
required: true, equalTo: "#captcha2"
}
},
messages: {
password2: "Please repeat the same password",
captcha: "The captcha you entered is wrong",
agree: "You have to be at least 16 years old and agree to the terms of service"
}
});
});
</script>
The html code for the form is even simpler, but I will show only a part of it.
<p>
<img src='/includes/captcha.php' />
</p>
<p>
<label for="Captcha">Captcha</label>
<em> *</em><input type="text" name="captcha" id="captcha" size="25"
class="require" minlength="5" />
<input type="hidden" name="captcha2" id="captcha2"
value="<?php echo $_SESSION['captcha'];?>" />
<?php echo $_SESSION['captcha']; ?>
Here is something weird. When I echo the session['captcha'] I get a different value than the value in the hidden field. I get the previous captcha when I echo it.
So let's say the captcha value is ABC. When I refresh the page the captcha+hidden field change into DEF. But when I echo session['captcha'] I still get ABC.
Why is this happening?
Here is the code of the captcha.php file;
<?php
session_start();
header("Content-type: image/png");
$string = '';
for ($i = 0; $i < 5; $i++) {
// this numbers refer to numbers of the ascii table (lower case)
$string .= chr(rand(97, 122));
}
$_SESSION['captcha'] = $string;
putenv('GDFONTPATH=' . realpath('.'));
$dir = 'musicals';
$image = imagecreatetruecolor(170, 60);
$black = imagecolorallocate($image, 0, 0, 0);
$color = imagecolorallocate($image, 129, 180, 79); // green
$white = imagecolorallocate($image, 255, 255, 255);
imagefilledrectangle($image,0,0,399,99,$white);
imagettftext ($image, 30, 0, 10, 40, $color, $dir, $_SESSION['captcha']);
imagepng($image);
?>
The problem is that your captcha generation is within the image, and that this image is only accessed after the form has been accessed. Your captcha is generated AFTER you show the form, this is why it's always one step behind.
Aside from that, it's a bad idea to store the captcha solution in a hidden field. A person, or a bot, can simply parse the website's source code and extract and use it as the captcha solution.
Be sure that captcha.php is run before html code. It looks like captcha.php generates image and probably it is inserted as an img in HTML. Image is got after page loading (generating HTML) so captcha code in session is not regenerated.
I belive that you inserted hidden element with captcha as an example. It is bad idea to show captcha code as a hidden element in form.

Categories