I have bitmao instance i convert this instance into base64string and send it to server over php function. Now i am decoding this string and calling imagecreatefromstring but this function is giving 500 internal server error. I want this image to be store into file.
My .net function is as follows:
Bitmap icon = new Bitmap("C:\\Users\\HP\\Desktop\\mun.ico");
System.IO.MemoryStream stream = new System.IO.MemoryStream();
icon.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
byte[] imageBytes = stream.ToArray();
// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
HttpWebRequest m_ObjRequest; //Request which needed to be sent to server
HttpWebResponse m_ObjResponse; // Response which is sent back from the server to the client
StreamReader reader = null; // making a stream reader to read the web pageand initialize it to null
string m_Url = "http://192.168.1.30/muneem/erp/uploadIcon.php"+ "?bitmap=" + base64String; // the url of that web page
string m_Response = "";
m_ObjRequest = (HttpWebRequest)WebRequest.Create(m_Url); // creating the url and setting the values
m_ObjRequest.Method = "GET";
m_ObjRequest.ContentType = "application/json; charset=utf-8";
//m_ObjRequest.ContentLength = 500;
m_ObjRequest.KeepAlive = false;
m_ObjResponse = (HttpWebResponse)m_ObjRequest.GetResponse(); // getting response from the server
using (reader = new StreamReader(m_ObjResponse.GetResponseStream())) // using stream reader to read the web page
{
m_Response = reader.ReadToEnd();
reader.Close(); // Close the StreamReader
}
m_ObjResponse.Close();
m_ObjRequest = null;
m_ObjResponse = null;
My php code to handle this encoded bitmap string is as follows:
$bitmap=$_GET['bitmap'];
$data = base64_decode($bitmap);
$im = imagecreatefromstring($data);
if ($im !== false) {
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);
}
else {
echo 'An error occurred.';
}
encoded bitmap string is as follows:
$bitmap="Qk02BAAAAAAAADYAAAAoAAAAEAAAABAAAAABACAAAAAAAAAAAADEDgAAxA4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="
why i am getting this error on imagecreate from string?
BMP format is not supported by imagecreatefromstring. Allowed formats are: JPEG, PNG, GIF, WBMP, and GD2.
Related
void _uploadFile(Event event) async {
print("called");
final files = uploadInput.files;
final file = files![0];
_fileNameController.text = file.name;
// Get the file contents as a List<int>
final reader = new FileReader();
reader.readAsArrayBuffer(file);
await reader.onLoad.first;
final contents = reader.result as List<int>;
// Encode the file contents as a base64 string
final encodedFile = base64Encode(contents);
var response = await http.post(Uri.parse("http://url/img_test/img.php"),
body: jsonEncode(<String, String>{
'file': encodedFile,
})
);
print(response.body);
if (response.statusCode == 200) {
// Handle the success case
print("ok");
} else {
// Handle the error case
print("try");
}
}
I all ready set as file in body but till it shows
Error shows in flutter
Warning: Undefined array key "file" in M:\WEB\htdocs\img_test\img.php on line 7
PHP API:
<?php
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
?>
your request post not send file, this string value, you can try decode in your php file like this
$base64string = "data:image/jpeg;base64,".$POST['file'];
list($type, $base64string) = explode(';', $base64string);
list(,$extension) = explode('/',$type);
list(,$base64string) = explode(',', $base64string);
$fileName = uniqid()'.'.$extension;
$imageFile = base64_decode($base64string);
file_put_contents($path.$fileName, $imageFile);
I'm returning image as base64 string in server side. In client side app takes this base64 string and convert it to byte[] and then to Bitmap and at the last step sets this bitmap to ImageView. My problem is returned image quality. It looks poor; I can see the pixels of this image...
Upload part
Client side (upload):
BitmapFactory.Options options = null;
options = new BitmapFactory.Options();
options.inSampleSize = 3;
bitmap = BitmapFactory.decodeFile(imgPath, options);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// Must compress the Image to reduce image size to make upload easy
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] byte_arr = stream.toByteArray();
// Encode Image to String
encodedString = Base64.encodeToString(byte_arr, 0);
Server side (accepts uploaded image):
$_image = $_REQUEST['image'];
$binary = base64_decode($_image);
// for inserting it to db...
$sql = "INSERT INTO users (`_profile_pic`) VALUES ('$_image')";
$connect->query($sql);
Accept part
Server side (gets base64 string from db)
$user_data = "SELECT _name, _profile_pic FROM users WHERE _id = {$_id}";
$data = $connect->query($user_data);
while ($row = $data->fetch(\PDO::FETCH_ASSOC))
$collectedResult[] = $row;
echo json_encode($collectedResult, JSON_UNESCAPED_UNICODE);
Client side (sets image to ImageView (problematic part) )
_picture = (ImageView) findViewById(R.id.profile_imageView);
byte[] decodedString = Base64.decode(profile_pic_value, Base64.DEFAULT);
Bitmap bmp = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
_picture.setImageBitmap(bmp);
At this moment I don't know how to restore or increase the quality.
Any helpful comment, answer appreciated.
Regards,
Mirjalal.
P.S This question maybe duplicate of another question(s), but I couldn't find duplicate one. :D
I found this but I don't know how to use.
It is possible that you loose color depth during decoding into RAM. Android has defaults as to which color format it decodes bitmaps. See following example which saves RAM but still maintains acceptable image quality.
public static Bitmap decodeBase64(String input) {
byte[] decodedByte = Base64.decode(input, Base64.DEFAULT);
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = false;
options.inPreferredConfig = Bitmap.Config.RGB_565;
return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length, options);
}
Take a closer look at the Bitmap.Config.RGB_565 parameter.
I'm working with android and try to create an app that able to upload several image to the server. I had tried to upload the image to my localhost using xampp, it works well. But when I try to upload to my enterprise server I can't find my file, in the other word. The file can't be written. I don't know what make it failed? This is my code
Upload tp XAMPP
Connection string private static final String url_photo = "http://192.168.7.110/blabla/base.php";
Path static final String path = "C:\\xampp\\htdocs\\psn_asset_oracle\\Images\\";
Upload to actual enterprise server
Connection String private static final String url_photo = "http://192.168.4.27/oracle/logam/am/data_images/android_image/base.php";
Path static final String path = "http://192.168.4.27/oracle/logam/am/data_images/android_image/";
My code to upload to server
params_p.add(new BasicNameValuePair("image_name_1",
image_name_1));
params_p.add(new BasicNameValuePair("image_name_2",
image_name_2));
params_p.add(new BasicNameValuePair("image_name_3",
image_name_3));
params_p.add(new BasicNameValuePair("image_name_4",
image_name_4));
json_photo = jsonParser.makeHttpRequest(url_photo, "POST", params_p);
ArrayList<NameValuePair> params_p = new ArrayList<NameValuePair>();
PHP code
if(isset($_POST["image_name_1"]) && isset($_POST["image_name_2"]) && isset($_POST["image_name_3"]) && isset($_POST["image_name_4"])
&& isset($_POST["image_1"]) && isset($_POST["image_2"]) && isset($_POST["image_3"]) && isset($_POST["image_4"]))
{
$image_name_1 = $_POST["image_name_1"];
$image_name_2 = $_POST["image_name_2"];
$image_name_3 = $_POST["image_name_3"];
$image_name_4 = $_POST["image_name_4"];
$image_1 = $_POST["image_1"];
$image_2 = $_POST["image_2"];
$image_3 = $_POST["image_3"];
$image_4 = $_POST["image_4"];
/*---------base64 decoding utf-8 string-----------*/
$binary_1=base64_decode($image_1);
$binary_2=base64_decode($image_2);
$binary_3=base64_decode($image_3);
$binary_4=base64_decode($image_4);
/*-----------set binary, utf-8 bytes----------*/
header('Content-Type: bitmap; charset=utf-8');
/*---------------open specified directory and put image on it------------------*/
$file_1 = fopen($image_name_1, 'wb');
$file_2 = fopen($image_name_2, 'wb');
$file_3 = fopen($image_name_3, 'wb');
$file_4 = fopen($image_name_4, 'wb');
/*---------------------assign image to file system-----------------------------*/
fwrite($file_1, $binary_1);
fclose($file_1);
fwrite($file_2, $binary_2);
fclose($file_2);
fwrite($file_3, $binary_3);
fclose($file_3);
fwrite($file_4, $binary_4);
fclose($file_4);
$response["message"] = "Success";
echo json_encode($response);
}
I've contact my DBA and asked to give me permission to write the file, and it still doesn't work. The error is json doesn't give "Success" as message that indicate the file failed to be written. I will appreciate any help. Thank you.
Does the file server allows write access permission? Sample of chmod, http://catcode.com/teachmod/
Is your enterprise server online? The IP address looks private to me, 192.168.4.27.
Dont use json use http post.
See below code
HttpClient client = new DefaultHttpClient();
String postURL = "your url";
HttpPost post = new HttpPost(postURL);
try {
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
ByteArrayBody bab = new ByteArrayBody(img, "image.jpg");
reqEntity.addPart("image", bab);
post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
Here img is your image in ByteArray format
The problem solved after my DBA give me another file path.
this is my first post. please be kind :)
i'm trying to get picture from media library (in WP 7), upload it using httpwebrequest, and save it to folder in the server. i succeed to convert the image to string of byte (but i suspect there are something wrong here), send the string using POST, and retrieve it in my php web page.
Everything seems to be working well, but when i convert the string of byte to jpeg (using imagecreatefromstring function) it always come up empty picture. here is my code in C# and php. I'm sorry for my English if it's not perfect (or far from perfect) :)
this is my c# code along with some comments
public partial class MainPage : PhoneApplicationPage
{
string uploadUri = #"http://192.168.138.1/meeshot/upload.php"; //php web page for retrieve and saving file in the server
string requestImageName = "picture"; //variable name for post ---- >$_POST['picture']
string postdata; //byte data generate using BitmapToByte function
// Constructor
public MainPage()
{
InitializeComponent();
}
PhotoChooserTask selectphoto = null;
Image image1 = new Image ();
private void button1_Click(object sender, RoutedEventArgs e) //user choosing photo from media library
{
selectphoto = new PhotoChooserTask();
selectphoto.Completed += new EventHandler<PhotoResult>(selectphoto_Completed);
selectphoto.Show();
}
void selectphoto_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
BinaryReader reader = new BinaryReader(e.ChosenPhoto);
image1.Source = new BitmapImage(new Uri(e.OriginalFileName));
HttpWebRequest req = HttpWebRequest.Create(
new Uri(this.uploadUri)) as HttpWebRequest;
postdata = BitmapToByte(image1); //convert image to byte. My suspisicion there is something wrong here
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.BeginGetRequestStream(HttpWebRequestButton2_RequestCallback, req);
}
}
private void HttpWebRequestButton2_RequestCallback(IAsyncResult result)
{
var req = result.AsyncState as HttpWebRequest;
using (var requestStream = req.EndGetRequestStream(result))
{
using (StreamWriter writer = new StreamWriter(requestStream))
{
writer.Write(requestImageName+"="+this.postdata); //writing "picture=bytedata"
writer.Flush();
}
}
req.BeginGetResponse(HttpWebRequestButton_Callback, req);
}
private void HttpWebRequestButton_Callback(IAsyncResult result)
{
var req = result.AsyncState as HttpWebRequest;
var resp = req.EndGetResponse(result);
var strm = resp.GetResponseStream();
var reader = new StreamReader(strm);
this.Dispatcher.BeginInvoke(() => {
this.DownloadedText.Text = reader.ReadToEnd(); //the web page will print byte data that has been sent using httpwebrequest. i can see that byte data has benn sent sucessfuly.
this.DownloadedText.Visibility = System.Windows.Visibility.Visible;
});
}
private Stream ImageToStream(Image image1)
{
WriteableBitmap wb = new WriteableBitmap(400, 400);
wb.Render(image1, new TranslateTransform { X = 400, Y = 400 });
wb.Invalidate();
Stream myStream = new MemoryStream();
wb.SaveJpeg(myStream, 400, 400, 0, 70);
return myStream;
}
private string BitmapToByte(Image image) //i suspect there is something wrong here
{
Stream photoStream = ImageToStream(image);
BitmapImage bimg = new BitmapImage();
bimg.SetSource(photoStream); //photoStream is a stream containing data for a photo
byte[] bytearray = null;
using (MemoryStream ms = new MemoryStream())
{
WriteableBitmap wbitmp = new WriteableBitmap(bimg);
wbitmp.SaveJpeg(ms, wbitmp.PixelWidth, wbitmp.PixelHeight, 0, 100);
ms.Seek(0, SeekOrigin.Begin);
bytearray = ms.GetBuffer();
}
string str = Convert.ToBase64String(bytearray);
return str;
}
and this is my code in php web page
if(isset($_REQUEST['picture'])) //check
{
$myFile = "picture.jpg";
$fh = fopen($myFile, 'wb') or die("can't open file");
$stringData = $_REQUEST['picture']."<br>";
$im = imagecreatefromstring($stringData);
if ($im) {
imagejpeg($im);
fwrite($fh, $im);
imagedestroy($im);
}
fclose($fh);
echo $stringData;
}
Please look at my question here: Photo upload with parameters to a PHP page
And my solution here: http://nediml.wordpress.com/2012/05/10/uploading-files-to-remote-server-with-multiple-parameters/
I'm trying to send an image from an sql database to an android client. I'm doing this by way of a php middleman. The code stops working due to a null returning of the method below.
My php code(works fine to encode image into base64(decoded the encoding and it worked)):
<?php
//get image
function ob_base64_encode($c) {
$a=base64_encode($c);
$arr = array('base64' => $a);
return json_encode($arr);
}
$image=resize(48,80,$image);
// And pass its name as a string
ob_start('ob_base64_encode');
imagepng($image);
ob_end_flush();
?>
My android code:
public static Bitmap getIm(String IP, int height, int width)
{
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//Network queries and gets response(works)
String result = Network.getResponse(IP, nameValuePairs);
//manually decode string since for some reason JSON decode won't work(also works)
String r=result.split(":\"")[1];
r=r.split("\"")[0];
//decode string
byte[] decodedString = Base64.decode(r, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
return decodedByte;
//returns null
}