How to resize a image in PHP

To resize a image in PHP you can use the following snippet.

Sample PHP

function ImageResize($imageName, $tempName, $maxWidth, $maxHeight)
{
	$extension = explode(".", $imageName);
	$extension = $extension[count($extension)-1];
 
	if($extension == "jpeg" || $extension == "jpg")
	{
		$image = imagecreatefromjpeg($tempName);
	}
        elseif($extension == "gif")
	{
		$image = imagecreatefromgif($tempName);
	}
	elseif($extension == "png")
	{
		$image = imagecreatefrompng($tempName);
	}
	
	$Width = imagesx($image);
	$Height = imagesy($image);
 
	if($Width <= $maxWidth && $Height <= $maxHeight)
	{
		return $image;
	}
 
	if($Width >= $Height) 
	{
		$newWidth = $maxWidth;
		$newHeight = $newWidth * $Height / $Width;
	}
	else 
	{
		$newHeight = $maxHeight;
		$newWidth = $Width / $Height * $newHeight;
	}
 
	$image2 = imagecreatetruecolor($newWidth, $newHeight);
	imagecopyresampled($image2, $image, 0, 0, 0, 0, floor($newWidth), floor($newWidth), $Width, $Height);
	return $image2; 
}

Please rate this snippet

How to download a image from url in C# and VB.NET

Sample C#

private static void DownloadImage(string url, string saveFilename)
{
	var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
	var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
	if ((httpWebResponse.StatusCode != HttpStatusCode.OK && 
		httpWebResponse.StatusCode != HttpStatusCode.Moved && 
		httpWebResponse.StatusCode != HttpStatusCode.Redirect) 
		|| !httpWebResponse.ContentType.StartsWith("image", StringComparison.OrdinalIgnoreCase))
	{
		return;
	}
	using (var stream = httpWebResponse.GetResponseStream())
	using (var fileStream = File.OpenWrite(saveFilename))
	{
		var bytes = new byte[4096];
		var read=0;
		do
		{
			if (stream == null) {continue;}
			read = stream.Read(bytes, 0, bytes.Length);
			fileStream.Write(bytes, 0, read);
		} while (read != 0);
	}
}

Sample VB.NET

Private Shared Sub DownloadImage(url As String, saveFilename As String)
	Dim httpWebRequest = DirectCast(WebRequest.Create(url), HttpWebRequest)
	Dim httpWebResponse = DirectCast(httpWebRequest.GetResponse(), HttpWebResponse)
	If (httpWebResponse.StatusCode <> HttpStatusCode.OK AndAlso httpWebResponse.StatusCode <> HttpStatusCode.Moved AndAlso httpWebResponse.StatusCode <> HttpStatusCode.Redirect) OrElse Not httpWebResponse.ContentType.StartsWith("image", StringComparison.OrdinalIgnoreCase) Then
		Return
	End If
	Using stream = httpWebResponse.GetResponseStream()
		Using fileStream = File.OpenWrite(saveFilename)
			Dim bytes = New Byte(4095) {}
			Dim read = 0
			Do
				If stream Is Nothing Then
					Continue Do
				End If
				read = stream.Read(bytes, 0, bytes.Length)
				fileStream.Write(bytes, 0, read)
			Loop While read <> 0
		End Using
	End Using
End Sub

Please rate this snippet