How to download a base64 image in PHP from a web service? - php

I admit I have a lot of trouble with this problem (I don't know much about PHP and SOAP.
I have to get product pictures for an ecommerce via a web service of a provider (SOAP).
As shown in the picture below, the product pictures are converted to base64.
Example for a product picture
I need to retrieve all the pictures to upload them in a folder on my site and write the path of each picture in a CSV file.
The code below allows me to retrieve all the products that are sent to me via the web service. I recover all the products with the function RecupEtatStock() then, with the help of a loop, for each product I search if there are images with the function RecupPhotoProduct().
$wsdl = "https://sinex-saas.com/B00UWSUG9Z34TN22/Services/WebServiceStandard.asmx?WSDL";
$client = new SoapClient($wsdl);
$password = "????";
$username = "????";
$reffab = 4;
$codefab = 2;
$i = 0;
$fp = fopen(plugin_dir_path(__FILE__).'file.csv', 'w+');
$dataRecupererEtatStock = RecupEtatStock($username, $password, $client);
foreach ($dataRecupererEtatStock as $fields) {
$dataRecupPhotoProduit = RecupPhotoProduit($username, $password, $client, $fields->CodeFab, $fields->RefFab, $i);
$fields->image = $dataRecupPhotoProduit;
fputcsv($fp, get_object_vars($fields));
$i+=1;
}
fclose($fp);
Here is what the RecupPhotoProduct() function looks like. If there is no picture, the function returns null, otherwise it retrieves what the save_image() function returns.
function RecupPhotoProduit($pUsername, $pPassword, $pClient, $pCodeFab, $pReffab, $pi) {
$optionsRecupererPhotoProduit = array(
'user' => $pUsername,
'password' => $pPassword,
'codeFab' => $pCodeFab,
'refFab' => $pReffab,
);
$responseRecupererPhotoProduit = $pClient->RecupererPhotoProduit($optionsRecupererPhotoProduit);
$array = get_object_vars($responseRecupererPhotoProduit);
if(empty($array)) {
$responseRecupererPhotoProduit = null;
} else {
$responseRecupererPhotoProduit = $responseRecupererPhotoProduit->RecupererPhotoProduitResult;
$responseRecupererPhotoProduit = save_image($responseRecupererPhotoProduit, $pi);
}
return $responseRecupererPhotoProduit;
}
The above function allows me to retrieve the string in "RetrievePhotoProductResult" from this XML result:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<RecupererPhotoProduitResponse xmlns="http://tempuri.org/">
<RecupererPhotoProduitResult>/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCACEAJoDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD3+iiigAooooAKKK5jxlZvq1pHpq3VxbROGaZoJNhYYwASOSOScewqoRcnZDSuUfEmq2k2pRw21zFLJCpD7HB2HnIJHTjr3rB3Fmz9/P4E5/lkfkKzINAs/DN/H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S7UGNHjUKrp25HXJ6H1FXNvOeOecsevbJ+vQ+hrsVpK5ZcXX9Vjt74taQT3Cu32OJX2h1HRZGPRsZORxVj+3yLm2iFkTbyRlpp9w/cnjaNvVsnPI6YrPCLjjpj3zgf+zL+opGjOfuKfYPxz2+jdvep9nEa02LT+JNVFjdG1tIILxZGW28xt8bIMfO+OQeuVHSm3Opajdais4vZFhERiNuwyjM3RyeufTHrVQqM5JA77iSfof6Gp4og3AQH+HZnGfVf6imoRWwilY20dtfWdvbjyovNLiMMcEk5bP+1nmuvt7YSSLCQP3xEYHTIP3sf8B3H8K5W6h1F1d9JTzL5cNCHUHc2cZx6joR7V0/g/QdftH+3eIr6Ke4KnbFHGAFJxzn2GR/wI8VNSooxaE3Y7GiiiuEgKKKKACiiigAooooAKKKKACiiigDlfFaq1xDkZ+Tkeo5rmJFCeYcZKhj83fBA5+oPNFFd9H4EWtiYIDLs5/1rJnPPyrkH6jpn061EVUoG2jmNWx2+Y4I+nf60UVoMQgLkjqN5z7r3/EdasxKvzAqCAyJg9we34dqKKTA19EQRa9tGTmQjLcnhW5+tdjRRXHX+IiW4UUUViIKKKKACiiigD//2Q==</RecupererPhotoProduitResult>
</RecupererPhotoProduitResponse>
</soap:Body>
</soap:Envelope>
So for this example, the MIME64 encoded text is :
/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCACEAJoDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJic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rJnPPyrkH6jpn061EVUoG2jmNWx2+Y4I+nf60UVoMQgLkjqN5z7r3/EdasxKvzAqCAyJg9we34dqKKTA19EQRa9tGTmQjLcnhW5+tdjRRXHX+IiW4UUUViIKKKKACiiigD//2Q==
And this is what my save_image() function looks like. It decodes the base64 image from the "RetrievePhotoProductResult" part of the previous XML and uploads it to my WordPress plugin directory.
function save_image( $base64_img, $title ) {
$base64_img = str_replace('data:image/png;base64,', '', $base64_img);
$base64_img = str_replace(' ', '+', $base64_img);
$data = base64_decode($base64_img);
$file = plugin_dir_path(__FILE__) . $title . '.png';
return file_put_contents($file, $data);
}
But here is my problem, the images download well in my directory. However, I can't open them.
For example, if I try to open them with Paint, this is what I get (Whether I open an image with Paint or not, it's the same thing. I think the problem is the base64 encoding):
Paint cannot read this file. It is not a valid bitmap file or its format is not currently supported.
And if I want to access an image from my ecommerce site, I have a simple white dot that appears:
I have a simple white dot that appears
And here is what the base64 string looks like after decoding:
the base64 string
Do you know how I could download a base64 image via a php web service?

<?php
$encode = "/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCACEAJoDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx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($encode);
$size = getImageSizeFromString($decode);
var_dump($size);
if (empty($size['mime']) || strpos($size['mime'], 'image/') !== 0) {
die('Base64 value is not a valid image');
}
$ext = substr($size['mime'], 6);
$img_file = "filename.{$ext}";
file_put_contents($img_file, $decode);
echo $ext;
?>
this will work for all valid images.

Related

Attempting to parse XML/JSON from an API output

OK... I am using PHP 5 (be gentle, still learning PHP). CURL is enabled. Attempting to load XML or JSON output from an API to an object and nothing happens. When I manually execute the URL in question, I get what I am expecting.
Here is my code:
class XmlToJson {
public function Parse ($url) {
$fileContents = file_get_contents($url);
$fileContents = str_replace(array("\n", "\r", "\t"), '', $fileContents);
$fileContents = trim(str_replace('"', "'", $fileContents));
$simpleXml = simplexml_load_string($fileContents);
$json = json_encode($simpleXml);
return $json;
}
}
$_MySQLServer = "localhost";
$_MySQLServerUserName = "";
$_MySQLServerPassword = "";
$_MySQLDatabaseName = "";
$_SSActiveWear_UserID = "*****";
$_SSActiveWear_APIKey = "*****";
$_SSActiveWear_APIBaseURL = "https://*****/v2";
$_CategoryURL = "/categories/";
$_StylesURL = "/styles/";
$_ProductsURL = "/products/";
$_SpecsURL = "/specs/";
$_SSActiveWear_MediaType = "xml";
//$_conn = mysqli_connect($_MySQLServer, $_MySQLServerUserName, $_MySQLServerPassword, $_MySQLDatabaseName);
//Insert or Update Categories
$_URL = $_SSActiveWear_APIBaseURL . $_CategoryURL;
$_URL = $_URL . "?mediatype=$_SSActiveWear_MediaType&UserName=$_SSActiveWear_UserID&Password=$_SSActiveWear_APIKey";
$OBJ = simplexml_load_string($_URL);
print_r($OBJ);
What am I doing wrong?
Edit 1
Added the following code:
$xml = simplexml_load_file($_URL) or die("Error: Cannot create object");
print_r($xml);
and it dies. Does that mean that there is something wrong with the code?
Try this :
$OBJ = simplexml_load_string(file_get_contents($_URL));
If you want to know why your code is not working, you are trying to load XML from URL but "simplexml_load_string" loads XML from string.
I FINALLY figured it out... More to the point I finally found a site on Google that helped. It is the first answer in fsockopen with http authentication problem.
So here is the code that works:
file_get_contents("https://$_SSActiveWear_UserID:$_SSActiveWear_APIKey#$_SSActiveWear_APIBaseURL$_CategoryURL/?mediatype=$_SSActiveWear_MediaType");
mediatype can be either json or xml

why does json_decode break when passed specific strings?

here is my function in a class called getminecraftprofile.php
basically it takes data from https://sessionserver.mojang.com/session/minecraft/profile/
dependant on the UUID of the user and gets an array that i can pick formation from.
the URL strings are base64 encoded so it decodes that as well.
public function getSkin()
{
$properties = $this->properties;
$encoded = json_encode($properties);
$imgUrl = json_decode(base64_decode(json_decode($encoded,true)[0]['value']),true) ['textures']['SKIN']['url'];
$img = file_get_contents($imgUrl);
echo($img);
}
this is the file that is passing in what user profile to find and get the skin of that profile. for most profiles it works perfectly and you can see it in action at http://jamesplanet.net/test/src/getskin.php?username=dinnerbone
<?php
include ($_SERVER["DOCUMENT_ROOT"] . '/test/src/getminecraftprofile.php' )?>
<?php
$profile = ProfileUtils::getProfile("useruser3");
//$result = $profile->getSkin();
$properties = $profile->getProperties();
$encoded = json_encode($properties);
$imgUrl = json_decode(base64_decode(json_decode($encoded,true)[0]['value']),true)['textures']['SKIN']['url'];
$img = file_get_contents($imgUrl);
var_dump($encoded);
echo('Texture URL Decoded: ' . $imgUrl );
it all grinds to a halt however if i say
$profile = ProfileUtils::getProfile("_jeb");
then it throws this at me
Warning: file_get_contents(): Filename cannot be empty in /Applications/AMPPS/www/test/src/getskin.php on line 10
string(908) "[{"name":"textures","value":"eyJ0aW1lc3RhbXAiOjE0MDM0ODE0Mjk2NDMsInByb2ZpbGVJZCI6IjdmM2ZjY2ZjYzUzOTQzNTdhZmEwMjExYTYyODc3MWU0IiwicHJvZmlsZU5hbWUiOiJfamViIiwiaXNQdWJsaWMiOnRydWUsInRleHR1cmVzIjp7fX0=","signature":"xIgM9w3MfZHMjlsZyrMDAF1CTAhhhhSWfjRqJgW3NNTCyotVkL9IMDN6ZzPIoNESFBlhwspxfKhrAC81+GlEUcFxLYilzO6qE+\/pYciNS78b9MxRK7R5xEoNNzFhXAyo9\/cW5X7V6bFxOB2MU9Fg7NXt\/B\/u4VypqGsbCA+OAm7Kgomlhkw3wkm1R1djfd5oBqwlCKhTWxt4k4mQJzThsqE5ffLdTcPeMoipezw4NHAV1QJfXZZlGsEDG\/KkzUDh6eOz+QufYvhcxGrOAfwJ4TzlLbu0QyT8IRIu0E5LY96sTSecWQ27W7TzsumXiXrkpOSLZrOi5yqGFMmfOEHqo8dLRnxhoNmyQpzN2rE4OvNBwKqvzOeRbigOzQSSg5xupydFFLdc20Pj9CXcTB18K12fXt6W8FJ+AzYUccPrSx\/1RJALkef9W5DCxNLOLLR5yIS8Irff3\/Gn2sRwTG8EXJz+6qRB50e02jdyTv9DZz853w+TAVoNtSkBB8W9aC08XUSCFFg1KAaLILkRi8H+76BE1pZKraPAoW8MpsUbd6J+6k0kU5lqdtiJZ1PtDssVMA+p9MwtOmQqD7n4hPXehULBv4+phQjZi37s1I6ZWYrQBE7raq3ZKfDx9ztccmHEyk\/VHSboo0QmtM8iCOCOC1l0Jv9QrV\/YQRZil03x+OQ="}]" Texture URL Decoded:
i know there is data there because its visible before the base64 decode.
where is it going wrong?
here is an example of what is being parsed
{"id":"069a79f444e94726a5befca90e38aaf5","name":"Notch","properties":[{"name":"textures","value":"eyJ0aW1lc3RhbXAiOjE0MDM0ODE0MjIwNDUsInByb2ZpbGVJZCI6IjA2OWE3OWY0NDRlOTQ3MjZhNWJlZmNhOTBlMzhhYWY1IiwicHJvZmlsZU5hbWUiOiJOb3RjaCIsImlzUHVibGljIjp0cnVlLCJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvYTExNmU2OWE4NDVlMjI3ZjdjYTFmZGRlOGMzNTdjOGM4MjFlYmQ0YmE2MTkzODJlYTRhMWY4N2Q0YWU5NCJ9LCJDQVBFIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvM2Y2ODhlMGU2OTliM2Q5ZmU0NDhiNWJiNTBhM2EyODhmOWM1ODk3NjJiM2RhZTgzMDg4NDIxMjJkY2I4MSJ9fX0=","signature":"TJieaNbZrHGmA7V3n8jn0V/ZVPXAy4EK44lxsh3kidK4JML8BEEZZjt/1eixbbXHGMH39e122UO7ehX2PIutuIIK7ZhvAo6wy8yMG34rPxjuyg0jzZe/tZjKv/kq7Bi78m6PErfwBsaUxjkCD3J0sqLXyvOy9rQ2CbYGKTxnVtOZGzxIaQqC5QH/2We704cMUJ3wIgN9FckppVA2E+DYu0G8iFlvYQnjxxIclokv3jOcPrYwVq0COWJaDrGd0+o+dKUfTfiT/k1OLBuceGDmqjb9CmcbEeTFFRJrmA6XEoA6OHZbLOMpIPLtEs8LbZqBH38Cuf+izPGLl1e28bITwPUdpABzvxaxKoYB3XYnWvtAqyfvzsCEgoBVnV7psx1W+kWU9xjCxC591457bollR2KVrSQBv7p0KBm4qVaVPKa01bjcMfcDDx5PRBIcL6XECVmKoeqh+qUrrf1Z9WN0l4OEujmRd8/tbJMjtJTdqCUZ5ak7urJHl8iTNNLqjx/Dsi47DeZvfUGdSC6ivpDIDBQv3myBLNnHqE7/+Z8DGKa+Bf/nQW0sMdVsNFOxIeiXMyXpWAHMw3/Ee21aMWEUq+rD8l4CD2FTZkQ/gv18y3y7CR9fYIKU+EPccnDUtyF+Y257UtCUag7i0vlkiBpIh46jhpjIkhR+iAG4URqQA6I="}]}

facebook graph api picture - get full url with .jpg

I am able to access my user image from FB with graph api by accessing the user id like so: https://graph.facebook.com/<USER_ID>/picture
However for my code to work, i need the real path to the image like http://profile.ak.fbcdn.net/hprofile-ak-snc6/******_**************_********_q.jpg
FBs doc shows that by adding ?callback=foo i can get an output, but in practice it doesnt seem to work.
any suggestions for getting the full path to my image with that .jpg extension from graph api or with the user id, thank you.
Callback is for javascript requests,
For php,try appending a redirect=false in url.
Do a curl request to,
https://graph.facebook.com/shaverm/picture?redirect=false
If you want to use callback in js,
$.getJSON('https://graph.facebook.com/zuck/picture?callback=?',function (resp) {
$('body').html(resp.data.url);
});​
Demo
Reference
*USE FOLLOWING YOU NEVER GET WRONG RESULT *
$URL='FB GRAPH API URL';
$headers = get_headers($URL, 1); // make link request and wait for redirection
if(isset($headers['Location'])) {
$URL = $headers['Location']; // this gets the new url
}
$url_arr = explode ('/',$URL);
$ct = count($url_arr);
$name = $url_arr[$ct-1];
$name_div = explode('.', $name);
$ct_dot = count($name_div);
$img_type = $name_div[$ct_dot -1];
$pos = strrpos($img_type, "&");//many time you got in url
if($pos)
{
$pieces = explode("&", $img_type);
$img_type = $pieces[0];
}
$imagename = imgnameyouwant'.'.$img_type;
$content = file_get_contents($URL);
file_put_contents("fbscrapedimages/$imagename", $content);

How to get user's profile pic url using graph api

Hi i m trying to get url of user's profile pic so I use following code
$userinfo = $facebook->api("/me/picture?type=large");
var_dump($userinfo);
but instead of returning url it returns NULL. Please help me why this is happening.
Thank you.
This is how we can get actual picture url
$URL='FB GRAPH API URL';
$headers = get_headers($URL, 1); // make link request and wait for redirection
if(isset($headers['Location'])) {
$URL = $headers['Location']; // this gets the new url
}
$url_arr = explode ('/',$URL);
$ct = count($url_arr);
$name = $url_arr[$ct-1];
$name_div = explode('.', $name);
$ct_dot = count($name_div);
$img_type = $name_div[$ct_dot -1];
$pos = strrpos($img_type, "&");
if($pos)
{
$pieces = explode("&", $img_type);
$img_type = $pieces[0];
}
$imagename = imgnameyouwant'.'.$img_type;
$content = file_get_contents($URL);
file_put_contents("fbscrapedimages/$imagename", $content);
If you know the [uid], you can simply use the following code
<img src="http://graph.facebook.com/[UID]/picture" />
You can also crop/resize the profile picture by providing height/width parameters.
Eg: https://graph.facebook.com/[UID]/picture?width=140&height=140
If you want to use standard sizes, try
<img src="http://graph.facebook.com/[UID]/picture?type=large" />
where type is one of {square,small,large}

Array contents not being passed fully from php client to a .NET web service

I want to pass an image as a byte array from php to a .NET web serice.
The php client is as follows:
<?php
class Image{
public $ImgIn = array();
}
$file = file_get_contents('chathura.jpg');
$ImgIn = str_split($file);
foreach ($ImgIn as $key=>$val) { $ImgIn[$key] = ord($val); }
$client = new SoapClient('http://localhost:64226/Service1.asmx?wsdl');
$result = $client->PutImage(new Image());
echo $result->PutImageResult;
//print_r($ImgIn);
?>
Here is the web method in ASP.NET web service:
[WebMethod]
public string PutImage(byte[] ImgIn)
{
System.IO.MemoryStream ms =
new System.IO.MemoryStream(ImgIn);
System.Drawing.Bitmap b =
(System.Drawing.Bitmap)Image.FromStream(ms);
b.Save("imageTest", System.Drawing.Imaging.ImageFormat.Jpeg);
return "test";
}
When I run this the image content is correctly read to ImgIm array in php client. (In this instance the image had 16992 elements.) However when the array is passed to the web service method it contains only 5 elements (the first 5 elements of the image)
Can I know what is the reason for the loss of data ? How can I avoid it ?
Thanks
file_get_contents returns the file contents as string which is not useful for binary files such as images. Try this:
$handle = fopen("chathura.jpg", "r");
$contents = fread($handle, filesize("chathura.jpg"));
fclose($handle);
$client = new SoapClient('http://localhost:64226/Service1.asmx?wsdl');
$result = $client->PutImage($contents);
Guys, it seems that it is not going to be any use to try and pass data as a byte array as PHP anyway converts it to a string when sending. This conversion seems to introduce control characters to the string, making it only send a part of the byte array. I got this to work by sending a base64 encoded string and decoding inside the server.
My client side code:
<?php
class Image{
public $ImgIn = '';
}
//ini_set("memory_limit","20M");
$imageData = file_get_contents('chathura.jpg');
$encodedData = base64_encode($imageData);
$Img = new Image();
$Img->ImgIn = $encodedData;
$client = new SoapClient('http://localhost:64226/Service1.asmx?wsdl');
$result = $client->PutImage($Img);
echo($result->PutImageResult);
?>
ASP .NET web service code:
[WebMethod]
public string PutImage(String ImgIn)
{
byte[] ImgInBytes = Convert.FromBase64String(ImgIn);
System.IO.MemoryStream ms =
new System.IO.MemoryStream(ImgInBytes);
System.Drawing.Bitmap b =
(System.Drawing.Bitmap)Image.FromStream(ms);
b.Save("C:\\imageTest.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
return "success";
}

Categories