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/
Related
Itext is a powerful toolkit for PDF generation, PDF programming, handling & manipulation. Java sample:
public void processPDF(String src, String dest) {
try {
PdfReader reader = new PdfReader(src);
PdfArray refs = null;
PRIndirectReference reference = null;
int nPages = reader.getNumberOfPages();
for (int i = 1; i <= nPages; i++) {
PdfDictionary dict = reader.getPageN(i);
PdfObject object = dict.getDirectObject(PdfName.CONTENTS);
if (object.isArray()) {
refs = dict.getAsArray(PdfName.CONTENTS);
ArrayList<PdfObject> references = refs.getArrayList();
for (PdfObject r : references) {
reference = (PRIndirectReference) r;
PRStream stream = (PRStream) PdfReader.getPdfObject(reference);
byte[] data = PdfReader.getStreamBytes(stream);
String dd = new String(data, "UTF-8");
dd = dd.replaceAll("#pattern_1234", "trueValue");
dd = dd.replaceAll("test", "tested");
stream.setData(dd.getBytes());
}
}
if (object instanceof PRStream) {
PRStream stream = (PRStream) object;
byte[] data = PdfReader.getStreamBytes(stream);
String dd = new String(data, "UTF-8");
System.out.println("content---->" + dd);
dd = dd.replaceAll("#pattern_1234", "trueValue");
dd = dd.replaceAll("This", "FIRST");
stream.setData(dd.getBytes(StandardCharsets.UTF_8));
}
}
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
stamper.close();
reader.close();
}
catch (Exception e) {
}
}
The question is how I can use this toolkit for PHP or there is any PHP toolkit like this?
I am using Yii2 Framework and just want to replace text inside a certain file (.doc, .docx, .pdf)
Original file:
Expected file after editing:
I was trying to compress a String in php using the following code.
<?php
$compressed = gzcompress('Compress me', 9);
echo $uncompressed;
?>
The compressed string is "xÚsÎÏ-(J-.VÈM½?".
But when tried to decompress this in java using the following function
public static String unzipString(String zippedText) {
String unzipped = null;
try {
byte[] zbytes = zippedText.getBytes("ISO-8859-1");
// Add extra byte to array when Inflater is set to true
byte[] input = new byte[zbytes.length + 1];
System.arraycopy(zbytes, 0, input, 0, zbytes.length);
input[zbytes.length] = 0;
ByteArrayInputStream bin = new ByteArrayInputStream(input);
InflaterInputStream in = new InflaterInputStream(bin);
ByteArrayOutputStream bout = new ByteArrayOutputStream(512);
int b;
while ((b = in.read()) != -1) {
bout.write(b);
}
bout.close();
unzipped = bout.toString();
} catch (IOException io) {
printIoError(io);
}
return unzipped;
}
I was getting null string..Please correct me if i did something wrong this code.
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="Qk02BAAAAAAAADYAAAAoAAAAEAAAABAAAAABACAAAAAAAAAAAADEDgAAxA4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="
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.
I already searched for a lot of different tutorials on how to upload an image from an windowsphonen 8 app to my php page (fileserver) - nothing works for me, so I 'm asking you.
This is my code to convert a Stream to Base64
string PhotoStreamToBase64(Stream PhotoStream)
{
MemoryStream memoryStream = new MemoryStream();
PhotoStream.CopyTo(memoryStream);
byte[] result = memoryStream.ToArray();
string base64img = System.Convert.ToBase64String(result);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < base64img.Length; i += 32766)
{
sb.Append(Uri.EscapeDataString(base64img.Substring(i, Math.Min(32766, base64img.Length - i))));
}
return sb.ToString();
}
I catch the Image using photoChooserTask (this works fine, but I dont get a Stream I can use for the other Method)
private void photoChooserTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
MessageBox.Show(e.ChosenPhoto.Length.ToString());
//Code to display the photo on the page in an image control named myImage.
System.Windows.Media.Imaging.BitmapImage bmp = new System.Windows.Media.Imaging.BitmapImage();
bmp.SetSource(e.ChosenPhoto);
MyImage.Source = bmp;
}
}
To Upload the image I tried this:
public void UploadImageAsync(Stream PhotoStream)
{
try
{
WebClient w = new WebClient();
w.Headers["Content-type"] = "application/x-www-form-urlencoded";
string data = "id=1" +
"&_fake_status=200" +
"&type=base64" +
"&image=" + PhotoStreamToBase64(PhotoStream);
w.UploadStringAsync(new Uri("http://myurl.de/php/app/changeimg.php", UriKind.Absolute), "POST", data);
}
catch (Exception ex)
{
}
}
The last part is my php file
function base64_to_image( $imageData, $outputfile ) {
$ifp = fopen( $outputfile, "wb" );
fwrite( $ifp, base64_decode( $imageData ) );
fclose( $ifp );
return( $outputfile );
}
if (isset($_POST['image'])) {
base64_to_jpeg($_POST['image'], "test".$_GET['id'].".jpg");
$file = 'people.txt';
$person = "Win";
file_put_contents($file, $person, FILE_APPEND | LOCK_EX);
}
else
{
die("no image data found");
$file = 'people.txt';
$person = "Fail";
file_put_contents($file, $person, FILE_APPEND | LOCK_EX);
}
I got all these code snippets from different sources and somehow thought it's the best "idea" I could find. Does anyone maybe have an example code for my Problem? I 'm really new to Windowsphone dev and I need some serious help on that problem.
First off all, do not use WebClient class, use HttpClient and its method PostAsync and then it completely dependent on your Web API implementation
I want to upload an Image i selected with the PhotoChooserTask.
The Selection itself works fine and i can open the Image.
I also already decoded it to Base64 (Works).
Since I can't find any working example on how to work with httpwebrequest on windowsphone I tried it the following way.
private void photoChooserTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
//Code to display the photo on the page in an image control named myImage.
System.Windows.Media.Imaging.BitmapImage bmp = new System.Windows.Media.Imaging.BitmapImage();
bmp.SetSource(e.ChosenPhoto);
MyImage.Source = bmp;
String str = BitmapToByte(MyImage);
String url = "http://klopper.puppis.uberspace.de/php/app/image.php?image="+ str;
LoadSiteContent(url);
}
}
The rest of the code is working fine.
I get: System.IO.FileNotFoundException
If I change the str to "test" it's working.
Is the problem, that the string is too long?
private void task_Completed(object sender, PhotoResult e)
{
if (e.TaskResult != TaskResult.OK)
return;
const int BLOCK_SIZE = 4096;
Uri uri = new Uri("http://localhost:4223/File/Upload", UriKind.Absolute);
WebClient wc = new WebClient();
wc.AllowReadStreamBuffering = true;
wc.AllowWriteStreamBuffering = true;
// what to do when write stream is open
wc.OpenWriteCompleted += (s, args) =>
{
using (BinaryReader br = new BinaryReader(e.ChosenPhoto))
{
using (BinaryWriter bw = new BinaryWriter(args.Result))
{
long bCount = 0;
long fileSize = e.ChosenPhoto.Length;
byte[] bytes = new byte[BLOCK_SIZE];
do
{
bytes = br.ReadBytes(BLOCK_SIZE);
bCount += bytes.Length;
bw.Write(bytes);
} while (bCount < fileSize);
}
}
};
// what to do when writing is complete
wc.WriteStreamClosed += (s, args) =>
{
MessageBox.Show("Send Complete");
};
// Write to the WebClient
wc.OpenWriteAsync(uri, "POST");
}
Reference
to post image file in windows phone 7 application