Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Image Being Overwritten

Status
Not open for further replies.

PCHomepage

Programmer
Feb 24, 2009
609
1
16
US
A form is converting (if necessary), resizing and uploading an image and is working fine but the same form also has other fields that I need to be able to edit without re-uploading the image, such as captions and that sort of thing, but I can't seem to figure out how to make it work without overwriting. The code is straightforward so can anyone see what I've missed? I even tried adding a conditional that should keep whatever is there as-is but it shouldn't even get to it with no image:

PHP:
if ($source = $_FILES["FileUpload"]["tmp_name"]) {
	if (file_exists($source)) {
		$size = @GetImageSize($source);

	 	$Types = array(1,2,3,6);
		if (!in_array($size[2], $Types)) {
			$imageupload->Image->Errors->AddError("<font color=\"red\">Only JPG, GIF, BMP or PNG format images may be used.</font>");
			$imageupload_OnValidate = 0;
		}	
		
		if ($size[0] < 0 || $size[1] < 0) {
			$imageupload->Image->Errors->AddError("<font color=\"red\">Bad image format!</font>");
			$imageupload_OnValidate = 0;
		}	
 
        if (isset($_POST['ResetWidth'])) {
        	$Width = $_POST['ResetWidth'];
        } else {
        	$Width = "";
        }

		$Sizes = imageNewsize($size[0], $size[1], $Width);
  		$NewImageHeight = $Sizes[0];
		$NewImageWidth = $Sizes[1];
		$FormatType = $size[2];

		$NewFormat = str_replace("mime/","",$size['mime']);

		if (isset($_POST['ThumbWidth'])) {
			$ThumbWidth = $_POST['ThumbWidth'];
		} else {
			$ThumbWidth = 50;
		}

		if ($NewImageHeight > 0 && $NewImageWidth > 0) {
			$imageupload->Image->SetValue(ConvertImage($source, $Width));
			$imageupload->Thumbnail->SetValue(ConvertImage($source, $ThumbWidth));
			$imageupload->ImageSize->SetValue(strlen(ConvertImage($source, $Width)));
			$imageupload->ImageWidth->SetValue($NewImageWidth);
			$imageupload->ImageHeight->SetValue($NewImageHeight);
			$imageupload->ImageFormat->SetValue($NewFormat);
		} else {
			$imageupload->Image->SetValue($imageupload->ds-f("Image"));
			$imageupload->Thumbnail->SetValue($imageupload->ds-f("Thumbnail"));
		}
	}
}
 
suspect that the devil is in the detail of the imageupload class.
 
Actually imageupload is simply the name I gave the form but it could have been named just about anything at all. I simply gave it an identifying name related to what it does but there is nothing in the name to cause the problem. In other words, the class actually has nothing to do with uploads.
 
this
Code:
$imageupload

is an object. we need the class to which the object is an instance.
 
In other words, the class actually has nothing to do with uploads.

That is as maybe, but from the code posted here it would appear that is DOES handle the naming of the uploaded image.

Chris.

Indifference will be the downfall of mankind, but who cares?
Time flies like an arrow, however, fruit flies like a banana.
Webmaster Forum
 
Yes, I know and sorry for not being clearer but it really isn't the culprit even though it seems an obvious candidate. It is, as I said, just a name and would work the same if I called it by my own name.

Anyway, the problem appears to be related to the conditionato that I posted above as the ConvertImage() function, which is what does the work, is being called regardless of whether an image is selected or not. I moved the "else" down to just inside the closing } where it makes more sense for it to be but it made no difference. That is actually where I had it originally but had moved it in an attemp to fix the problem and had forgotten to put it back before posting the code. Is there some better way to detect if a file has actually been selected? I suppose as a work-around I could modify ConvertImage() to output the original image but that's not really a fix!
 
It is really difficult to answer without seeing the class from.which $imageupload is an object and the convertimage function.

 
Honestly, the class $imageupload has absolutely nothing to do with it and it's generated code anyway so I can't change it if I wanted to, other than giving it a different name, adding, removing or renaming items in it. The code I posted above is all that does the work other than the actual custom ConvertImage() function and a couple other similar ones that are called from it. However, just to satisfy your curiosity, here is $imageupload:

Code:
class clsRecordimageupload { //imageupload Class @4-6EA119FA

//Variables @4-9E315808

    // Public variables
    public $ComponentType = "Record";
    public $ComponentName;
    public $Parent;
    public $HTMLFormAction;
    public $PressedButton;
    public $Errors;
    public $ErrorBlock;
    public $FormSubmitted;
    public $FormEnctype;
    public $Visible;
    public $IsEmpty;

    public $CCSEvents = "";
    public $CCSEventResult;

    public $RelativePath = "";

    public $InsertAllowed = false;
    public $UpdateAllowed = false;
    public $DeleteAllowed = false;
    public $ReadAllowed   = false;
    public $EditMode      = false;
    public $ds;
    public $DataSource;
    public $ValidatingControls;
    public $Controls;
    public $Attributes;

    // Class variables
//End Variables

//Class_Initialize Event @4-0D338B88
    function clsRecordimageupload($RelativePath, & $Parent)
    {

        global $FileName;
        global $CCSLocales;
        global $DefaultDateFormat;
        $this->Visible = true;
        $this->Parent = & $Parent;
        $this->RelativePath = $RelativePath;
        $this->Errors = new clsErrors();
        $this->ErrorBlock = "Record imageupload/Error";
        $this->DataSource = new clsimageuploadDataSource($this);
        $this->ds = & $this->DataSource;
        $this->ReadAllowed = true;
        $this->Visible = (CCSecurityAccessCheck("4;2;3") == "success");
        if($this->Visible)
        {
            $this->ReadAllowed = $this->ReadAllowed && CCUserInGroups(CCGetGroupID(), "4;2;3");
            $this->InsertAllowed = CCUserInGroups(CCGetGroupID(), "4;3");
            $this->UpdateAllowed = CCUserInGroups(CCGetGroupID(), "4");
            $this->DeleteAllowed = CCUserInGroups(CCGetGroupID(), "4");
            $this->ComponentName = "imageupload";
            $this->Attributes = new clsAttributes($this->ComponentName . ":");
            $CCSForm = explode(":", CCGetFromGet("ccsForm", ""), 2);
            if(sizeof($CCSForm) == 1)
                $CCSForm[1] = "";
            list($FormName, $FormMethod) = $CCSForm;
            $this->EditMode = ($FormMethod == "Edit");
            $this->FormEnctype = "application/x-[URL unfurl="true"]www-form-urlencoded";[/URL]
            $this->FormSubmitted = ($FormName == $this->ComponentName);
            $Method = $this->FormSubmitted ? ccsPost : ccsGet;
            $this->Link = new clsControl(ccsLabel, "Link", "Link", ccsText, "", CCGetRequestParam("Link", $Method, NULL), $this);
            $this->Link->HTML = true;
            $this->ImageDescription = new clsControl(ccsTextBox, "ImageDescription", "<em>Description</em>", ccsText, "", CCGetRequestParam("ImageDescription", $Method, NULL), $this);
            $this->ImageDescription->Required = true;
            $this->ImageCategory = new clsControl(ccsListBox, "ImageCategory", "<em>Image Category</em>", ccsInteger, "", CCGetRequestParam("ImageCategory", $Method, NULL), $this);
            $this->ImageCategory->DSType = dsTable;
            $this->ImageCategory->DataSource = new clsDBsunvirgin();
            $this->ImageCategory->ds = & $this->ImageCategory->DataSource;
            $this->ImageCategory->DataSource->SQL = "SELECT ID, CategoryName, ImageType \n" .
"FROM lookup_imagecategories {SQL_Where} {SQL_OrderBy}";
            $this->ImageCategory->DataSource->Order = "CategoryName";
            list($this->ImageCategory->BoundColumn, $this->ImageCategory->TextColumn, $this->ImageCategory->DBFormat) = array("ID", "CategoryName", "");
            $this->ImageCategory->DataSource->Parameters["expr102"] = "Discography";
            $this->ImageCategory->DataSource->wp = new clsSQLParameters();
            $this->ImageCategory->DataSource->wp->AddParameter("1", "expr102", ccsText, "", "", $this->ImageCategory->DataSource->Parameters["expr102"], "", false);
            $this->ImageCategory->DataSource->wp->Criterion[1] = $this->ImageCategory->DataSource->wp->Operation(opBeginsWith, "CategoryName", $this->ImageCategory->DataSource->wp->GetDBValue("1"), $this->ImageCategory->DataSource->ToSQL($this->ImageCategory->DataSource->wp->GetDBValue("1"), ccsText),false);
            $this->ImageCategory->DataSource->Where = 
                 $this->ImageCategory->DataSource->wp->Criterion[1];
            $this->ImageCategory->DataSource->Order = "CategoryName";
            $this->ImageCategory->Required = true;
            $this->ResetWidth = new clsControl(ccsListBox, "ResetWidth", "ResetWidth", ccsInteger, "", CCGetRequestParam("ResetWidth", $Method, NULL), $this);
            $this->ResetWidth->DSType = dsListOfValues;
            $this->ResetWidth->Values = array(array("0", "No Resize"), array("185", "Discography (185)"), array("250", "General Purpose (250)"), array("500", "Large Format (500)"));
            $this->ResetWidth->Required = true;
            $this->ChangeFormat = new clsControl(ccsRadioButton, "ChangeFormat", "ChangeFormat", ccsInteger, "", CCGetRequestParam("ChangeFormat", $Method, NULL), $this);
            $this->ChangeFormat->DSType = dsListOfValues;
            $this->ChangeFormat->Values = array(array("0", "No Conversion"), array("1", "Convert"));
            $this->HideWatermark = new clsControl(ccsCheckBox, "HideWatermark", "HideWatermark", ccsBoolean, $CCSLocales->GetFormatInfo("BooleanFormat"), CCGetRequestParam("HideWatermark", $Method, NULL), $this);
            $this->HideWatermark->CheckedValue = true;
            $this->HideWatermark->UncheckedValue = false;
            $this->WatermarkLevel = new clsControl(ccsListBox, "WatermarkLevel", "WatermarkLevel", ccsInteger, "", CCGetRequestParam("WatermarkLevel", $Method, NULL), $this);
            $this->WatermarkLevel->DSType = dsTable;
            $this->WatermarkLevel->DataSource = new clsDBsunvirgin();
            $this->WatermarkLevel->ds = & $this->WatermarkLevel->DataSource;
            $this->WatermarkLevel->DataSource->SQL = "SELECT Level, LevelName \n" .
"FROM watermark_levels {SQL_Where} {SQL_OrderBy}";
            $this->WatermarkLevel->DataSource->Order = "Level";
            list($this->WatermarkLevel->BoundColumn, $this->WatermarkLevel->TextColumn, $this->WatermarkLevel->DBFormat) = array("Level", "LevelName", "");
            $this->WatermarkLevel->DataSource->Order = "Level";
            $this->WatermarkLevel->Required = true;
            $this->ThumbWidth = new clsControl(ccsListBox, "ThumbWidth", "ThumbWidth", ccsInteger, "", CCGetRequestParam("ThumbWidth", $Method, NULL), $this);
            $this->ThumbWidth->DSType = dsListOfValues;
            $this->ThumbWidth->Values = array(array("50", "50px wide"), array("75", "75px wide"), array("125", "125px wide"), array("150", "150px wide"), array("200", "200px wide"));
            $this->Thumbnail = new clsControl(ccsHidden, "Thumbnail", "Thumbnail", ccsMemo, "", CCGetRequestParam("Thumbnail", $Method, NULL), $this);
            $this->Insert = new clsButton("Insert", $Method, $this);
            $this->Update = new clsButton("Update", $Method, $this);
            $this->Delete = new clsButton("Delete", $Method, $this);
            $this->Cancel = new clsButton("Cancel", $Method, $this);
            $this->ShowThumbnail = new clsControl(ccsLabel, "ShowThumbnail", "ShowThumbnail", ccsText, "", CCGetRequestParam("ShowThumbnail", $Method, NULL), $this);
            $this->ShowThumbnail->HTML = true;
            $this->ShowImage = new clsControl(ccsLabel, "ShowImage", "ShowImage", ccsText, "", CCGetRequestParam("ShowImage", $Method, NULL), $this);
            $this->ShowImage->HTML = true;
            $this->ImageFormat = new clsControl(ccsHidden, "ImageFormat", "ImageFormat", ccsText, "", CCGetRequestParam("ImageFormat", $Method, NULL), $this);
            $this->ImageSize = new clsControl(ccsHidden, "ImageSize", "ImageSize", ccsInteger, "", CCGetRequestParam("ImageSize", $Method, NULL), $this);
            $this->ImageWidth = new clsControl(ccsHidden, "ImageWidth", "ImageWidth", ccsInteger, "", CCGetRequestParam("ImageWidth", $Method, NULL), $this);
            $this->ImageHeight = new clsControl(ccsHidden, "ImageHeight", "ImageHeight", ccsInteger, "", CCGetRequestParam("ImageHeight", $Method, NULL), $this);
            $this->ID = new clsControl(ccsHidden, "ID", "ID", ccsInteger, "", CCGetRequestParam("ID", $Method, NULL), $this);
            $this->Image = new clsControl(ccsHidden, "Image", "Image", ccsMemo, "", CCGetRequestParam("Image", $Method, NULL), $this);
            $this->FileUpload = new clsControl(ccsTextBox, "FileUpload", "FileUpload", ccsText, "", CCGetRequestParam("FileUpload", $Method, NULL), $this);
            if(!$this->FormSubmitted) {
                if(!is_array($this->ResetWidth->Value) && !strlen($this->ResetWidth->Value) && $this->ResetWidth->Value !== false)
                    $this->ResetWidth->SetText(185);
                if(!is_array($this->ChangeFormat->Value) && !strlen($this->ChangeFormat->Value) && $this->ChangeFormat->Value !== false)
                    $this->ChangeFormat->SetText(0);
                if(!is_array($this->HideWatermark->Value) && !strlen($this->HideWatermark->Value) && $this->HideWatermark->Value !== false)
                    $this->HideWatermark->SetValue(false);
                if(!is_array($this->WatermarkLevel->Value) && !strlen($this->WatermarkLevel->Value) && $this->WatermarkLevel->Value !== false)
                    $this->WatermarkLevel->SetText(50);
                if(!is_array($this->ThumbWidth->Value) && !strlen($this->ThumbWidth->Value) && $this->ThumbWidth->Value !== false)
                    $this->ThumbWidth->SetText(50);
            }
        }
    }
//End Class_Initialize Event
 
It isn't curiosity. It is trying to get to the root cause of a problem you have asked us to help with.

Is that really every method in that class? It looks like only the constructor.

You will see that this class references plenty of other objects too which will need to get chased down.

You haven't supplied convertimage either.

What seems to be happening is that you're using the same form code to editband create an image. On creation all is well. On editing the form code runs and either fails as the source image exists or overwrites with a blank image as nothing is uploaded the second time. Absent of the code the solution would be to write a different form for editing and decouple it from the imageupload process. Just treat as an ordinary database change identified by some unique id.

And I've said this loads of times before but generated php from frameworks really suck. Makes administration a nightmare. I know you have a different perspective so this is a comment and warning to other readers.
 
Yes, it is a constructor which is what I was trying to say and I originally posted only the code where I had the question since the rest was superfluous. All of the other objects that the class references are similar and are just constructors. There is no possibility whatsoever that the problem is anywhere but in the code I posted so there is nothing else to chase down.

What I need to know is whether there is a better, more concise way to detect if a file has been selected. My code apparently "thinks" I am uploading an image whether I've selected one or not so it is running the ConvertImage() function when it should not so it likely then outputs nothing and "nothing" gets inserted. Here is ConvertImage() which is working just as it should:

PHP:
function ConvertImage($ImgFile, $ImgSize) {
    if (file_exists($ImgFile)) :
        list($Imgwidth, $Imgheight, $ImgType, $attr) = getimagesize($ImgFile);

        switch ($ImgType) :
            case 1 : $src = imagecreatefromgif($ImgFile);  break;
            case 2 : $src = imagecreatefromjpeg($ImgFile); break;
            case 3 : $src = imagecreatefrompng($ImgFile);  break;
            case 6 : $src = imagecreatefrombmp($ImgFile); break; // Custom function
        endswitch;

		if ($src !== FALSE) :
			$Sizes = imageNewsize($Imgwidth, $Imgheight, $ImgSize); // Function outputs an array of height and width
			$newHeight = $Sizes[0];
			$newWidth = $Sizes[1];

			$tmp = imagecreatetruecolor($newWidth, $newHeight);
				if ($ImgType == 1 || $ImgType == 3):
					$transparent = imagecolorallocatealpha($tmp, 255, 255, 255, 127);
					imagefill($tmp, 0, 0, $transparent);
					imagealphablending($tmp, FALSE);
					imagesavealpha($tmp, TRUE);
				endif;

		   imagecopyresampled($tmp, $src, 0, 0, 0, 0,$newWidth, $newHeight, $Imgwidth, $Imgheight);

			ob_start();
				switch ($ImgType) :
					case 1 : imagegif($tmp); break;
					case 2 : imagejpeg($tmp, null, 100); break;
					case 3 : imagepng($tmp, null); break;
					case 6 : imagejpeg($tmp, null, 100); break;
					default : imagejpeg($tmp, null, 100);
				endswitch;
				$result = ob_get_contents();
			ob_end_clean();	

			imagedestroy($tmp);
		endif;
		
	endif;
  return $result;
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top