I have jquery plugin which send image in base 64 encoded format which i want to store in server
here is what I've tried
$post = json_decode($_POST['file'], true); $data = $post['output']['image'];
$data = str_replace('data:image/png;base64,', '', $data);
$data = str_replace(' ', '+', $data);
$data = base64_decode($data);
require('/home/example/public_html/files/image/class.upload.php');
$code = md5(time());
$handle = new upload($data);
if ($handle->uploaded) {
$handle->file_new_name_body = "$code";
$handle->mime_check = true;
$handle->allowed = array('image/*');
$handle->image_convert = 'jpg';
$handle->jpeg_quality = 70;
$handle->image_resize = true;
$handle->image_x = 600;
$handle->image_ratio_y = 600;
$handle->process('/home/example/public_html/files/blog/img/');
if ($handle->processed) {
$file_name = $handle->file_dst_name;
} else {
echo "error";
}
}
My above code image upload class works on every image but i'm unable to uploade base 64 encoded image, how can i achieve that
The upload class you're using doesn't support feeding base64 directly into it. You're best off using this method to save a temporary version to your directory first, using the class to do what you need to do, then deleting it:
$data = str_replace('data:image/png;base64,', '', $data);
$data = str_replace(' ', '+', $data);
$data = base64_decode($data);
require('/home/example/public_html/files/image/class.upload.php');
$code = md5(time());
$write_dir = "/home/example/public_html/files/blog/img/";
$temp_code = "temp_".$code;
$ifp = fopen($write_dir.$temp_code, "wb");
fwrite($ifp, $data);
fclose($ifp);
$handle = new upload($write_dir.$temp_code);
if ($handle->uploaded) {
$handle->file_new_name_body = "$code";
$handle->mime_check = true;
$handle->allowed = array('image/*');
$handle->image_convert = 'jpg';
$handle->jpeg_quality = 70;
$handle->image_resize = true;
$handle->image_x = 600;
$handle->image_ratio_y = 600;
$handle->process($write_dir);
if ($handle->processed) {
$file_name = $handle->file_dst_name;
unlink($write_dir.$temp_code);
} else {
echo "error";
}
}
Related
I have some problem with uploading image into PHP server. In this case, first I'l get image from gallery than create the output as base64, then I convert base64 to file using stream, then upload it into server. Here is my code.
UploadActivity.kt
private fun updatePhoto(variable: String, file: Bitmap, userId: String) {
val encode = encodedImage(file)
val outputDir: File = this.cacheDir
val f = File.createTempFile(userId, ".jpeg", outputDir)
var fos: FileOutputStream? = null
try {
fos = FileOutputStream(f)
} catch (e: FileNotFoundException) {
e.printStackTrace()
}
try {
fos!!.write(encode)
fos.flush()
fos.close()
} catch (e: IOException) {
e.printStackTrace()
}
val builder = MultipartBody.Builder()
builder.setType(MultipartBody.FORM)
val requestFile = f.asRequestBody(getMimeType(f.path)?.toMediaTypeOrNull())
builder.addFormDataPart(variable, f.name, requestFile)
builder.addFormDataPart("userId", userId)
val apiService = ApiInterface.create()
val call = apiService.updatePicture(builder.build())
call.enqueue(object : Callback<UserModel> {
override fun onResponse(
call: Call<UserModel>,
response: retrofit2.Response<UserModel>?
) {
val jsonObject = response!!.body()
val returnedResponse = jsonObject!!.status
if (returnedResponse!!.trim { it <= ' ' } == "200") {
val intent = Intent(this#UploadPreviewActivity, ProfileActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
startActivity(intent)
finish()
} else {
Toast.makeText(
this#UploadPreviewActivity,
"Terjadi kesalahan, harap coba kembali.",
Toast.LENGTH_SHORT
).show()
}
}
override fun onFailure(call: Call<UserModel>, t: Throwable) {
call.cancel()
Toast.makeText(
this#UploadPreviewActivity,
"Harap periksa koneksi internet anda",
Toast.LENGTH_LONG
).show()
}
})
}
Interface.kt
#POST("user-update-picture")
fun updatePicture(#Body requestBody: RequestBody): Call<UserModel>
Upload.php
function resize_image($file) {
$src = imagecreatefromstring($file);
if (!$src) return false;
$width = imagesx($src);
$height = imagesy($src);
$newwidth = $width*0.5;
$newheight = $height*0.5;
$dst = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
ob_start();
imagejpeg($dst);
$data = ob_get_contents();
ob_end_clean();
return $data;
}
function decodeImage($picturePath, $dir, $dir_thumb, $userId){
$image = str_replace('data:image/png;base64,', '', str_replace('[removed]', '', $picturePath));
$image = str_replace(' ', '+', $image);
$data = base64_decode($image);
$data2 = base64_decode($picturePath);
$thumb = $this->resize_image($data2);
$file = './files/images/'.$dir.'/'.$userId.'.jpg';
$upload = file_put_contents($file, $data);
$file2 = './files/images/'.$dir_thumb.'/'.$userId.'.jpg';
$upload2 = file_put_contents($file2, $thumb);
}
public function picture_post(){
date_default_timezone_set('Asia/Jakarta');
$Date = date('Y-m-d H:i:s');
$userId = filter_var($this->post('userId'), FILTER_SANITIZE_NUMBER_INT);
if (isset($_FILES['userPhotoPath']['tmp_name']) && !empty($_FILES['userPhotoPath']['tmp_name']) && $_FILES['userPhotoPath']['tmp_name']!=NULL) {
$photoPath = $_FILES['userPhotoPath']['tmp_name'];
$photoType = $_FILES['userPhotoPath']['type'];
$photoData = file_get_contents($photoPath);
$userPhotoPath = 'data:' . $photoType . ';base64,' . base64_encode($photoData);
if(file_exists("./files/images/users/".$userId.".jpg")){
$unlink = unlink("./files/images/users/".$userId.".jpg");
}
if(file_exists("./files/images/users_thumb/".$userId.".jpg")){
$unlink2 = unlink("./files/images/users_thumb/".$userId.".jpg");
}
$this->decodeImage($userPhotoPath, 'users', 'users_thumb', $userId);
}else{
$userPhotoPath = NULL;
}
}
Then when I upload the file from android I get this error in Okhttp Log
Message: imagecreatefromstring(): Data is not in a recognized format
Backtrace:
Function: imagecreatefromstring
I don't know why, because my PHP code work with my web version of this application with same upload method using javascript
I solve this issue by my self and this my mistake,
I change this code
function decodeImage($picturePath, $dir, $dir_thumb, $userId){
$image = str_replace('data:image/png;base64,', '', str_replace('[removed]', '', $picturePath));
$image = str_replace(' ', '+', $image);
$data = base64_decode($image);
$data2 = base64_decode($picturePath);
$thumb = $this->resize_image($data2);
$file = './files/images/'.$dir.'/'.$userId.'.jpg';
$upload = file_put_contents($file, $data);
$file2 = './files/images/'.$dir_thumb.'/'.$userId.'.jpg';
$upload2 = file_put_contents($file2, $thumb);
}
into this
function decodeImage($picturePath, $dir, $dir_thumb, $userId){
$image = str_replace('data:image/png;base64,', '', str_replace('[removed]', '', $picturePath));
$image = str_replace(' ', '+', $image);
$data = base64_decode($image);
$thumb = $this->resize_image($data);
$file = './files/images/'.$dir.'/'.$userId.'.jpg';
$upload = file_put_contents($file, $data);
$file2 = './files/images/'.$dir_thumb.'/'.$userId.'.jpg';
$upload2 = file_put_contents($file2, $thumb);
}
This is my little mistake I forgot about the rezise_image content requirement, after change that code this upload work 100% without any problem again.
When I upload an image file to the host, why the file repeat filename extension again ? I check the filename in the host is like test.jpg.jpg
Here is the code:
$uploadPath = "../../upload/Image/";
$handle = new Upload($_FILES['pic'], 'zh_TW');
if($handle->uploaded){
$pic=$_FILES['pic']['name'];
if($pic != ''){
$filename = $pic;
}
else{
$microSecond = microtime();
$filename = substr($microSecond, 11, 20).substr($microSecond, 2, 8);
}
$handle->file_new_name_body = $filename;
$handle->image_resize = true;
$handle->image_ratio_y = true;
$handle->image_x = 212;
$handle->image_ratio_fill = true;
$handle->allowed = array('image/*');
$handle->file_overwrite = true;
$handle->process($uploadPath);
if($handle->processed){
$handle->file_dst_name = $filename;
}
else{
echo "<script>";
echo "alert('$handle->error');";
echo "history.back();";
echo "</script>";
die;
}
}
else{
$filename = $_POST['currentPic'];
}
Base on your conditions. you can just get the name onle part by explode function.
if($handle->uploaded){
$pic=$_FILES['pic']['name'];
if($pic != ''){
//$filename = $pic;
$filename = explode(".",$pic)[0];
}
else{
$microSecond = microtime();
$filename = substr($microSecond, 11, 20).substr($microSecond, 2, 8);
}
This is so you dont need to modify your class, also if you modify your class you will get trouble on the "ELSE" side of your condition that will cause additional spending time where to get the extension.
I try to upload data with different type of extension with codeigniter but I have constraints file it does not go into the folder that I go. i try to make some config according to what i need, please help ..
function add_module_external(){
$id_module = '9090909';
$file_data = array();
$file_data2 = array();
$image_data = array();
$config_video = array();
$config_image["file_name"] = $id_module;
$config_image["upload_path"] = "./assets/file/image-module/";
$config_image["overwrite"] = TRUE;
$config_image["allowed_types"] = "gif|jpg|png|";
$this->load->library('upload', $config_image);
$this->upload->initialize($config_image);
$upload_background = $this->upload->do_upload('other_image');
if($upload_background){
$image_data = $this->upload->data();
$image = $image_data['file_name'];
}else{
$image = $this->input->post('background');
}
// pdf and ppt upload
$config_file['file_name'] = $id_module;
$config_file['upload_path'] = '/assets/file/materi-module/';
$config_file['overwrite'] = TRUE;
$config_file['allowed_types'] = 'pdf';
$this->load->library('upload', $config_file);
$this->upload->initialize($config_file);
$upload_pdf = $this->upload->do_upload('pdf_data');
if($upload_pdf){
$file_data = $this->upload->data();
$content = $file_data["file_name"];
}else if($upload_ppt){
$file_data2 = $this->upload->data();
$content = $file_data2["file_name"];
}else if($upload_video){
$config_video = $this->upload->data();
$content = $config_video["file_name"];
}else{
$content = $this->input->post("text_data");
}
$query = $this->my_module->new_module($image, $id_module, $content);
redirect($this->agent->referrer());
}
I'm using class.upload.php for images. Resizing works correctly with name and extension into the folder, but i have a problem storing the name into mysql database. There's no file extension (.jpg, .gif etc)... why? how can i resolve the problem?
Thanks
/* ========== SCRIPT UPLOAD MULTI IMAGES ========== */
include('class.upload.php');
$dir_dest="../../images/gallery/";
$files = array();
foreach ($_FILES['fleImage'] as $k => $l) {
foreach ($l as $i => $v) {
if (!array_key_exists($i, $files))
$files[$i] = array();
$files[$i][$k] = $v;
}
}
foreach ($files as $file) {
$handle = new Upload($file);
if ($handle->uploaded) {
$mainame = $handle->file_dst_name;
$db_name = str_replace(" ","_",$mainame);
$image1 = md5(rand() * time()) . ".$db_name";
$parts = explode(".",$image1);
$extension = end($parts);
$result_big = str_replace("." . $extension,"",$image1);
$handle->file_new_name_body = $result_big;
$handle->image_resize = true;
$handle->image_x = 460;
$handle->image_ratio_y = true;
// $handle->image_y = 400;
$handle->Process($dir_dest);
//Thumbnail
$db_name = str_replace(" ","_",$mainame);
$image1 = md5(rand() * time()) . ".$db_name";
$parts = explode(".",$image1);
$extension = end($parts);
$result_small = str_replace("." . $extension,"",$image1);
$handle->file_new_name_body = $result_small;
$handle->image_resize = true;
$handle->image_x = 180;
$handle->image_ratio_y = true;
// $handle->image_y = 120;
$handle->Process($dir_dest);
// we check if everything went OK
if ($handle->processed) {
header("Location: index.php"); //echo 'image resized';
$handle->clean();
$query_img="INSERT into tbl_images (file_name, pd_image, pd_thumbnail) VALUES('$nome','$result_big', '$result_small')";
$result2 = dbQuery($query_img);
} else {
echo 'error : ' . $handle->error;
}
}
}
// END SCRIPT UPLOAD MULTI IMAGES
header("Location: index.php");
}
You are removing the extension with this code
$result_big = str_replace("." . $extension,"",$image1);
I dont know why you do that. anyway you can add it back by adding following line after the $handle->file_new_name_body = $result_big;
$handle->file_new_name_ext = $extension;
You have replaced the extention with empty string here using str_replace
$result_small = str_replace("." . $extension,"",$image1);
and here
$result_big = str_replace("." . $extension,"",$image1);
update below lines just add .$extension at the end
$handle->file_new_name_body = $result_big.$extension;
and
$handle->file_new_name_body = $result_small.$extension;
just change query like this
$query_img="INSERT into tbl_images (
file_name,
pd_image,
pd_thumbnail
) VALUES (
'$nome',
'{$result_big}.{$extension}',
'{$result_small}.{$extension}')";
I will suggest you to have same filename for pd_image and pd_thumbnail, just prefix thumb with thumb_ that will make your life easier in front end.
this way you can access any image thumbnail just by prefixing it with thumb_ with pd_image and you don't have to store pd_thumbnail in database.
I am using class.upload.php and I have the code all working except I want to extend the my script to work with multiple file uploads I read the documentation on the website and was able to figure it out. However I need my image files output like m_1234_1, m_1234_3, m_1234_4 and so on... How does one make it so that $handle->file_new_name_body = $new_name; starts with $new_name.'1' and continues adding 1 to every iteration?
<?php
$id = $_GET['id'];
if(isset($_POST['submit'])) {
// define variables
$new_name = 'm_'.$id.'_';
$thumb_name = 't_'.$id.'_';
$ext = 'jpg';
$upload_path = 'images/uploads/'.$id.'/'; // will not work with /images/
$full_src = $upload_path.$new_name.'.'.$ext;
// end define variables
$files = array();
foreach ($_FILES['userfile'] as $k => $l) {
foreach ($l as $i => $v) {
if (!array_key_exists($i, $files))
$files[$i] = array();
$files[$i][$k] = $v;
}
}
foreach ($files as $file) {
$handle = new upload($_FILES['userfile']);
if ($handle->uploaded) {
// save uploaded image 458 x 332
$handle->file_new_name_body = $new_name;
$handle->image_convert = $ext;
$handle->allowed = array('image/*');
$handle->jpeg_quality = 95;
$handle->image_resize = true;
$handle->image_ratio_crop = true;
$handle->image_x = 458;
$handle->image_y = 332;
$handle->file_overwrite = true;
$handle->auto_create_dir = true;
$handle->process($upload_path);
if ($handle->processed) {
mysql_select_db($db);
mysql_query("UPDATE projects SET last_modified=NOW(), project_image_1 = '".$full_src."' WHERE id = $id") or die(mysql_error());
} else {
echo '<div class="ec-messages messages-error">';
echo 'Error: ' . $handle->error;
echo '</div>';
}
// create thumbnail 104 x 76
$handle->file_new_name_body = $thumb_name;
$handle->image_convert = $ext;
$handle->allowed = array('image/*');
$handle->jpeg_quality = 90;
$handle->image_resize = true;
$handle->image_ratio_crop = true;
$handle->image_x = 104;
$handle->image_y = 76;
$handle->file_overwrite = true;
$handle->auto_create_dir = true;
$handle->process($upload_path);
if ($handle->processed) {
echo '<div class="ec-messages messages-success">Image successfully uploaded and added to database (thumnails created)<br>Redirecting to projects main...</div><br><img src="'.$full_src.'" class="display-image">';
echo "<script>setTimeout(\"location.href='projects.php?msg=insert';\",2000);</script>";
include('Templates/footer_exit.php');
$handle->clean();
exit;
} else {
// no error here, error will be handled by the first script
}
}
}
}
?>
UPDATED (now working):
<?php
$id = $_GET['id'];
if(isset($_POST['submit'])) {
// define variables
$ext = 'jpg';
$upload_path = 'images/uploads/'.$id.'/'; // will not work with /images/
// end define variables
$files = array();
foreach ($_FILES['userfile'] as $k => $l) {
foreach ($l as $i => $v) {
if (!array_key_exists($i, $files))
$files[$i] = array();
$files[$i][$k] = $v;
}
}
$counter = 1;
foreach ($files as $file) {
//$append = rand(100,99999);
$new_name = 'm_'.$id;
$thumb_name = 't_'.$id;
$handle = new upload($file);
if ($handle->uploaded) {
// save uploaded image 458 x 332
$count = $counter++;
$nn = sprintf("%s_%d", $new_name, $count);
$full_src = $upload_path.$nn.'.'.$ext;
$handle->file_new_name_body = $nn;
$handle->image_convert = $ext;
$handle->allowed = array('image/*');
$handle->jpeg_quality = 95;
$handle->image_resize = true;
$handle->image_ratio_crop = true;
$handle->image_x = 458;
$handle->image_y = 332;
$handle->file_overwrite = true;
$handle->auto_create_dir = true;
$handle->process($upload_path);
if ($handle->processed) {
mysql_select_db($db);
mysql_query("UPDATE projects SET last_modified=NOW(), project_image_".$count." = '".$full_src."' WHERE id = $id") or die(mysql_error());
} else {
echo '<div class="ec-messages messages-error">';
echo 'Error: ' . $handle->error;
echo '</div>';
}
// create thumbnail 104 x 76
$tn = sprintf("%s_%d", $thumb_name, $count);
$handle->file_new_name_body = $tn;
$handle->image_convert = $ext;
$handle->allowed = array('image/*');
$handle->jpeg_quality = 90;
$handle->image_resize = true;
$handle->image_ratio_crop = true;
$handle->image_x = 104;
$handle->image_y = 76;
$handle->file_overwrite = true;
$handle->auto_create_dir = true;
$handle->process($upload_path);
if ($handle->processed) {
echo 'Done!';
/*
echo '<div class="ec-messages messages-success">Image successfully uploaded and added to database (thumnails created)<br>Redirecting to projects main...</div><br><img src="'.$full_src.'" class="display-image">';
echo "<script>setTimeout(\"location.href='projects.php?msg=insert';\",2000);</script>";
include('Templates/footer_exit.php');
$handle->clean();
exit;
*/
} else {
// no error here, error will be handled by the first script
}
}
}
}
?>
You might define
$new_name = 'm_'.$id.'_';
$counter = 1; // File counter
at the beginning, and replace that line with
$handle->file_new_name_body = sprintf("%s.%d", $new_name, $counter++);
so that 'file' would become 'file.1.jpg', and so on.