OS X 10.8.3C++
We have base64 encode and decode functions in our code.
However, I want to base64 encode a string from my terminal and use it in my code so our functions can decode it when it needs to be used.
How does one base64 encode a string from a terminal?
I'm struggling to find any resources on this online, which is concerning.I've been reading about UCS-2 and UTF-16 woes, but I can't find a solution.
I need to get a value from an input:
var val = $('input').val()and encode it to base64, treating the text as utf-16, so:
this is a testbecomes:
dABoAGkAcwAgAGkAcwAgAGEAIAB0AGUAcwB0AA==and not the below, which you get treating it as UTF-8:
dGhpcyBpcyBhIHRlc3Q= Im trying to upload a base64 image to a FaceBook page using Node.js. I have managed to get the upload working with all the multipart data etc should I read the file from the filesystem (ie. using fs.readFileSync('c:\a.jpg')
However, should I use the base64 encoded image and try upload it, it give me the following error : {"error":{"message":"(#1) An unknown error occurred","type":"OAuthException","code":1}}
I have tried converting it to binary by new Buffer(b64string, 'base64'); and uploading that, but no luck.
I have been struggling with this for 3 days now, so anyhelp would be greatly appreciated.
Edit : If anyone also knows how I could convert the base64 to binary and successfully upload it, that would also work for me.
Thanks very much
Edit : Code Snippet
var postDetails = separator + newlineConstant + 'Content-Disposition: form-data;name="access_token"' + newlineConstant + newlineConstant + accessToken + newlineConstant + separator;postDetails = postDetails + newlineConstant + 'Content-Disposition: form-data; name="message"' + newlineConstant + newlineConstant + message + newlineConstant;//Add the Image informationvar fileDetailsString = '';var index = 0;var multipartBody = new Buffer(0);images.forEach(function (currentImage) { fileDetailsString = fileDetailsString + separator + newlineConstant + 'Content-Disposition: file; name="source"; filename="Image' + index + '"' + newlineConstant + 'Content-Type: image/jpeg' + newlineConstant + newlineConstant; index++; multipartBody = Buffer.concat([multipartBody, new Buffer(fileDetailsString), currentImage]); //This is what I would use if Bianry data was passed in currentImage = new Buffer (currentImage.toString('base64'), 'base64'); // The following lines are what I would use for base64 image being passed in (The appropriate lines would be enabled/disabled if I was using Binary/base64) multipartBody = Buffer.concat([multipartBody, new Buffer(fileDetailsString), currentImage]);});multipartBody = Buffer.concat([new Buffer(postDetails), multipartBody, new Buffer(footer)]); I am working on encoding the selected image from the gallery and want to send it to the server.I succeeded to send name and description of the product which is text form.but, I don't know how to encode image and send it to string form.On the server side, I need to decode it with php.My code is...
public class AddEditWishlists extends Activity {// Client-Server - Start //////////////////////JSONParser jsonParser = new JSONParser();// url to create new productprivate static String url_create_product = "http://10.56.43.91/android_connect/create_product.php";// JSON Node namesprivate static final String TAG_SUCCESS = "success";InputStream is;// Client-Server - End ////////////////////////Define Variablesprivate EditText inputname;private EditText inputnote;private Button upload;private Bitmap yourSelectedImage;private ImageView inputphoto;private Button save;private int id;private byte[] blob=null;byte[] image=null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.add_wishlist); setUpViews();}private void setUpViews() { inputname = (EditText) findViewById(R.id.inputname); inputnote = (EditText) findViewById(R.id.inputnote); inputphoto = (ImageView) findViewById(R.id.inputphoto); Bundle extras = getIntent().getExtras(); if (extras != null) { id=extras.getInt("id"); inputname.setText(extras.getString("name")); inputnote.setText(extras.getString("note")); image = extras.getByteArray("blob"); String encodedImage = Base64.encodeToString(image , Base64.DEFAULT); if (image != null) { if (image.length > 3) { inputphoto.setImageBitmap(BitmapFactory.decodeByteArray(image,0,image.length)); } } } //Image Upload Button upload = (Button) findViewById(R.id.upload); upload.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("image/*"); startActivityForResult(intent, 0); } }); // Save the data save = (Button) findViewById(R.id.save); // Save하면 발생되는 이벤트 save.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (inputname.getText().length() != 0) { AsyncTask<Object, Object, Object> saveContactTask = new AsyncTask<Object, Object, Object>() { @Override protected Object doInBackground(Object... params) { saveContact(); // Client-Server - Start ////////////////////////////////////// String name = inputname.getText().toString(); String description = inputnote.getText().toString(); //String photo = inputphoto.getContext().toString(); encodedImage = yourSelectedImage.toString(); // Building Parameters List<NameValuePair> params1 = new ArrayList<NameValuePair>(); params1.add(new BasicNameValuePair("name", name)); params1.add(new BasicNameValuePair("description", description)); params1.add(new BasicNameValuePair("photo", encodedImage)); Log.v("log_tag", System.currentTimeMillis()+".jpg"); // getting JSON Object // Note that create product url accepts POST method JSONObject json = jsonParser.makeHttpRequest(url_create_product, "POST", params1); // check log cat fro response Log.d("Create Response", json.toString()); // check for success tag try { int success = json.getInt(TAG_SUCCESS); Log.v("log_tag", "In the try Loop" ); if (success == 1) { // closing this screen finish(); } else { // failed to create product } } catch (JSONException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Object result) { finish(); } }; saveContactTask.execute((Object[]) null); } else { AlertDialog.Builder alert = new AlertDialog.Builder( AddEditWishlists.this); alert.setTitle("Error In Save Wish List"); alert.setMessage("You need to Enter Name of the Product"); alert.setPositiveButton("OK", null); alert.show(); } } });}// If users save data, this will act (data -> db) private void saveContact() { if(yourSelectedImage!=null){ ByteArrayOutputStream outStr = new ByteArrayOutputStream(); yourSelectedImage.compress(CompressFormat.JPEG, 100, outStr); blob = outStr.toByteArray(); } else{blob=image;} // Change Text type to string type to save in the DB SQLiteConnector sqlCon = new SQLiteConnector(this); if (getIntent().getExtras() == null) { sqlCon.insertWishlist(inputname.getText().toString(), inputnote.getText().toString(), blob); } else { sqlCon.updateWishlist(id, inputname.getText().toString(), inputnote.getText().toString(), blob); }}@Overrideprotected void onActivityResult(int requestCode, int resultCode,Intent resultdata) { super.onActivityResult(requestCode, resultCode, resultdata); switch (requestCode) { case 0: if (resultCode == RESULT_OK) { Uri selectedImage = resultdata.getData(); String[] filePathColumn = { MediaStore.Images.Media.DATA }; Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null); cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(filePathColumn[0]); String filePath = cursor.getString(columnIndex); cursor.close(); // Convert file path into bitmap image using below line. yourSelectedImage = BitmapFactory.decodeFile(filePath); inputphoto.setImageBitmap(yourSelectedImage); } }}what I am working on is the part here
if (extras != null) { id=extras.getInt("id"); inputname.setText(extras.getString("name")); inputnote.setText(extras.getString("note")); image = extras.getByteArray("blob"); //Here..I encoded the image ***********Is it correct?********** String encodedImage = Base64.encodeToString(image , Base64.DEFAULT); if (image != null) { if (image.length > 3) { inputphoto.setImageBitmap(BitmapFactory.decodeByteArray(image,0,image.length)); } } }and...
// Client-Server - Start ////////////////////////////////////// String name = inputname.getText().toString(); String description = inputnote.getText().toString();// this line should be modified i guess.... String encodedImage = yourSelectedImage.toString(); // Building Parameters List<NameValuePair> params1 = new ArrayList<NameValuePair>(); params1.add(new BasicNameValuePair("name", name)); params1.add(new BasicNameValuePair("description", description));// This line should be modified i guess..params1.add(new BasicNameValuePair("photo", encodedImage)); Log.v("log_tag", System.currentTimeMillis()+".jpg"); // getting JSON Object // Note that create product url accepts POST method JSONObject json = jsonParser.makeHttpRequest(url_create_product, "POST", params1); // check log cat fro response Log.d("Create Response", json.toString());I wrote annotation where should be corrected....I think that part makes error..
and one more question is that on the server side, how format should it be to receive the encoded photo? Varchar? char?..
Thank you in advance.
PHP's base64_encode is returning a different string to the linux base64 command.Why is this?
PHP:
$ php<?phpecho base64_encode('test');?>dGVzdA==Linux base64:
$ echo 'test' | base64dGVzdAo= Please note that by viewing our site you agree to our use of cookies (see Privacy for details). You will only see this message once.