latest update.. i have codes for uploading image.. but i do not know whats going to do for this code..? source code from http://monstercoda.wordpress.com/2012/04/15/android-image-upload-tutorial-part-i/
codes are the following:
public class MainActivity extends Activity {
Uri currImageURI;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button gallery_btn = (Button)findViewById(R.id.gallerybtn);
gallery_btn.setOnClickListener(new OnClickListener(){
public void onClick(View view){
//to open up a gallery browser
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture.."),1);
(getRealPathFromURI(currImageURI);
}
});
}
// To handle when an image is selected from the browser
public void onActivityResult(int requestCode, int resultCode, Intent data){
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
// currImageURI is the global variable I’m using to hold the content:
currImageURI = data.getData();
String s = ("Current image Path is ----->" + getRealPathFromURI(currImageURI));
TextView tv_path = (TextView) findViewById(R.id.path);
tv_path.setText(getRealPathFromURI(currImageURI));
}
HttpUploader uploader = new HttpUploader();
try {
uploader.execute(getRealPathFromURI(currImageURI));
}
}
//Convert the image URI to the direct file system path of the image file
public String getRealPathFromURI( Uri contentUri) {
String [] proj={MediaStore.Images.Media.DATA};
android.database.Cursor cursor = managedQuery(contentUri,
proj, // Which columns to return
null, // WHERE clause; which rows to return (all rows)
null, // WHERE clause selection arguments (none)
null); // Order-by clause (ascending by name)
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String c = cursor.getString(column_index);
return c;
}
}
my httpUploader is simple as simple as they provide:
public class HttpUploader extends AsyncTask<String, Void, String> {
protected String doInBackground(String... path) {
String outPut = null;
for (String sdPath : path) {
Bitmap bitmapOrg = BitmapFactory.decodeFile(sdPath);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
//Resize the image
double width = bitmapOrg.getWidth();
double height = bitmapOrg.getHeight();
double ratio = 400/width;
int newheight = (int)(ratio*height);
System.out.println("———-width" + width);
System.out.println("———-height" + height);
bitmapOrg = Bitmap.createScaledBitmap(bitmapOrg, 400, newheight, true);
//Here you can define .PNG as well
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 95, bao);
byte[] ba = bao.toByteArray();
String ba1=Base64.encodeBytes(ba);
String k = "uploading image now ——–" + ba1 ;
Log.e("k contains", k);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//store path for image name and id for each profile id.
nameValuePairs.add(new BasicNameValuePair("image", ba1));
nameValuePairs.add(new BasicNameValuePair("path", sdPath));
nameValuePairs.add(new BasicNameValuePair("id", id));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("192.168.1.1/upload.php"); // which request for $_POST['image'];
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// print responce
outPut = EntityUtils.toString(entity);
Log.i("GET RESPONSE—-", outPut);
//is = entity.getContent();
Log.e("log_tag ******", "good connection");
bitmapOrg.recycle();
} catch (Exception e) {
Log.e("log_tag ******", "Error in http connection " + e.toString());
}
}
return outPut;
}
}
PHP file saving to the database:
if (isset($base)) {
$base = $_REQUEST["image"];
$filepath = $_REQUEST["path"];
$id = $_REQUEST["id"];
$image_name = "/image/".$filepath;
// base64 encoded utf-8 string
$binary = base64_decode($base);
// binary, utf-8 bytes
header("Content-Type: bitmap; charset=utf-8");
$file = fopen($image_name, "wb");
fwrite($file, $binary);
fclose($file);
$result = "UPDATE profile SET image = '$image_name' WHERE RID = '$id'");
if(mysql_affected_rows > 0){
echo json_encode ("success!");
}else{
echo json_encode ("failed!");
}
} else {
die("No POST");
}
?>
or if the code is not appropriate... any guidnce can be provided for beginner? there are too many versions of code out there.. and i can slightly understand this because it is simpler than others.
Remove the .get() from your asynctask call.
Put HttpUploader uploader = new HttpUploader(); and Object image_name = uploader.execute(getRealPathFromURI(currImageURI)); without the .get() in onActivityResult(). Because only in onActivityResult() you know the filename.
Related
Generally I had code for Image picker and I had following code in a Fragment but whenever I run the data is sent to server but image is not sent.
private void startingCameraIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
System.out.println("====onActivityResult");
if (requestCode == SELECT_PICTURE && resultCode == getActivity().RESULT_OK) {
selectedImageUri = data.getData();
String[] projection = {MediaStore.MediaColumns.DATA};
CursorLoader cursorLoader = new CursorLoader(getActivity(), selectedImageUri, projection, null, null,
null);
Cursor cursor = cursorLoader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
cursor.moveToFirst();
filepath = cursor.getString(column_index);
System.out.println("file path is :----" + filepath);
System.out.println("file selectedImageUri :----" + selectedImageUri);
imageview_pic.setVisibility(View.VISIBLE);
Picasso.with(getActivity()).load(selectedImageUri).fit().into(imageview_pic);
} else if (requestCode == CAMERA_PIC_REQUEST && resultCode == getActivity().RESULT_OK) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.PNG, 100, bytes);
// thumbnail.createScaledBitmap(thumbnail,1024,768,true);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// ivImage.setImageBitmap(thumbnail);
imageview_pic.setVisibility(View.VISIBLE);
System.out.println("===Image Path : " + destination);
System.out.println("===thumbnail : " + thumbnail);
filepath = String.valueOf(destination);
Log.d("Image path",filepath);
imageview_pic.setImageBitmap(thumbnail);
} else {
}
}
//----------------------------------------------------------------------------------------------------------
class postadd extends AsyncTask<String, String, JSONObject>
{
String title = ettitle.getText().toString();
String name = etname.getText().toString();
String city = etcity.getText().toString();
String district = text.getText().toString();
String taluka = text1.getText().toString();
String contact = etcontact.getText().toString();
String price = etprice.getText().toString() + " / " + item;
String details = etdetails.getText().toString();
// String img=selectedImageUri.getPath().toString();
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "Image Upload URL";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "result";
#Override
protected void onPreExecute() {
pd.show();
}
#Override
protected JSONObject doInBackground(String... args) {
try {
HashMap<String, String> map = new HashMap<>();
map.put("file_upload",filepath);
map.put("add_title", title);
map.put("cat", cat_id);
map.put("sub_cat", finalsubcatid);
map.put("add_price", price);
map.put("add_description", details);
map.put("add_name", name);
map.put("add_phone", contact);
map.put("add_city", city);
map.put("add_district", district);
map.put("add_taluka", taluka);
Log.d("request", "starting");
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", map);
if (json != null) {
Log.d("JSON result", json.toString());
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(JSONObject json) {
if (pd != null && pd.isShowing())
{
pd.dismiss();
}
if (json != null) {
/* Toast.makeText(SignUp.this, json.toString(),
Toast.LENGTH_LONG).show();
*/
try {
// result = json.getInt(TAG_SUCCESS);
result = json.getString(TAG_MESSAGE);
} catch (JSONException e) {
e.printStackTrace();
}
}
if(result.equals("true"))
{
Toast.makeText(getActivity(),"Add Posted Successfull",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getActivity(),"Post Not Done...",Toast.LENGTH_SHORT).show();
}
}
}
The above code is used in PostAddFragment from where Camera intent is call to click and when post add button is hit it upload image to server.
You cannot send image like this, you may need to send it as an Multipart Entity or you can send it as a String also using Base64 encoding which can be hectic.
String path = Utils.getPath(getApplicationContext(), uri);
Bitmap bitmap = BitmapFactory.decodeFile(path);
byte[] imageBytes = getBytesFromBitmap(bitmap);
final String image = Base64.encodeToString(imageBytes, Base64.DEFAULT);
image will be your string of image
map.put("image ", image );
and on server side you have to get it as s String and decode it using Base64 decoder
I want to set an image in ImageView, I am retrieving the image path in my first activity and I am passing it via Intent as a String to second activity. In the second activity I set the path to an ImageView. It's working properly, and I need to upload that picture to a server. So I decoded the path to a bitmap. It throws an OutOfMemoryError. How to resolve this issue?
And when I use front camera, there is no issues. Image is uploaded successfully. The problem is with the images taken by front camera of the device. What is the solution for this problem? Can anyone help?
Here is the code to convert the image path to a string and passing it via Intent:
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Cursor cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.Images.Media.DATA, MediaStore.Images.Media.DATE_ADDED, MediaStore.Images.ImageColumns.ORIENTATION}, MediaStore.Images.Media.DATE_ADDED, null, "date_added ASC");
if(cursor != null && cursor.moveToFirst())
{
do {
Uri uri = Uri.parse(cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA)));
photoPath = uri.toString();
}while(cursor.moveToNext());
cursor.close();
try {
Intent intent = new Intent(MainActivity.this, ImageUploadActivity.class);
intent.putExtra("ImagePath", photoPath);
MainActivity.this.startActivity(intent);
}
catch (Exception e)
{
Toast.makeText(MainActivity.this, "Method invoked"+photoPath, Toast.LENGTH_SHORT).show();
}
}
Receiving Intent in Second Activity:
Intent camIntent = getIntent();
camPicPath = camIntent.getExtras().getString("ImagePath");
imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(camPicPath));
Toast.makeText(getApplicationContext(), "PATHe"+camPicPath, Toast.LENGTH_SHORT).show();
bitmap = (BitmapFactory.decodeFile(camPicPath));
Method to Upload the file:
class ImageUploadTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... unsued) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost("http://11.10.11.15/test/upload.php");
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
/* entity.addPart("uploaded_file", new ByteArrayBody(data,
"myImage.jpg"));*/
// String newFilename= filename.concat("file");
// newFilename=filename+newFilename;
entity.addPart("uploaded_file", new ByteArrayBody(data,
filename));
// Log.e(TAG, "Method invoked");
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost,
localContext);
BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
String aux = "";
while ((aux = reader.readLine()) != null) {
builder.append(aux);
}
String sResponse = builder.toString();
return sResponse;
} catch (Exception e) {
if (dialog.isShowing())
dialog.dismiss();
Toast.makeText(getApplicationContext(), "Exception Message 1", Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
return null;
}
Use the following method:
Bitmap bm = ShrinkBitmap(imagefile, 300, 300);
image.setImageBitmap(bm);
Bitmap ShrinkBitmap(String file, int width, int height) {
BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeFile(file, bmpFactoryOptions);
int heightRatio = (int) Math.ceil(bmpFactoryOptions.outHeight / (float) height);
int widthRatio = (int) Math.ceil(bmpFactoryOptions.outWidth / (float) width);
if (heightRatio > 1 || widthRatio > 1) {
if (heightRatio > widthRatio) {
bmpFactoryOptions.inSampleSize = heightRatio;
} else {
bmpFactoryOptions.inSampleSize = widthRatio;
}
}
bmpFactoryOptions.inJustDecodeBounds = false;
bitmap = BitmapFactory.decodeFile(file, bmpFactoryOptions);
return bitmap;
}
Or use inSampleSize when setting the image bitmap like this:
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
imageView.setImageBitmap(BitmapFactory.decodeFile(path, options));
you can add below property to application tag of manifiest file for high memory.
android:largeHeap="true"
hi i am developing an application that needs to post some images in jpeg format to server in multi-part file form , i have written below given code for this but it gives following response,
01-15 00:32:14.119: I/System.out(7598): file is upload {"status":"error","message":"Please, Specify valid Parameter for file"}
please someone help me. Thanks in advance .
Here is my activity code
public class SendPostActivity extends Activity implements OnClickListener {
private Context appContext;
private String messageType;
HashMap<String, String> fileList = new HashMap<String, String>();
public String finalImagePath = null;
// number of images to select
private static final int PICK_IMAGE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
setContentView(R.layout.activity_send_post);
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
appContext = this;
initComponent();
}
private void initComponent() {
((Button) findViewById(R.id.btnLeftNav)).setVisibility(View.VISIBLE);
((Button) findViewById(R.id.btnRightNav)).setVisibility(View.VISIBLE);
((Button) findViewById(R.id.btnRightNav))
.setBackgroundResource(R.drawable.send_btn);
((Button) findViewById(R.id.btnLeftNav)).setOnClickListener(this);
((Button) findViewById(R.id.btnRightNav)).setOnClickListener(this);
((ImageView) findViewById(R.id.imageviewCamera))
.setOnClickListener(this);
((ImageView) findViewById(R.id.imageviewGallery))
.setOnClickListener(this);
((TextView) findViewById(R.id.txtAudioSong)).setOnClickListener(this);
((TextView) findViewById(R.id.txtVedioSong)).setOnClickListener(this);
Typeface face = Typeface.createFromAsset(getAssets(),
"fonts/GeosansLight.ttf");
((TextView) findViewById(R.id.txtHeading)).setTypeface(face);
((EditText) findViewById(R.id.edtMessage)).setTypeface(face);
((TextView) findViewById(R.id.txtHeading)).setText("Send Post");
}
#Override
public void finish() {
super.finish();
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.btnLeftNav) {
this.finish();
} else if (v.getId() == R.id.btnRightNav) {
String strPostMessage = ((EditText) findViewById(R.id.edtMessage))
.getEditableText().toString().trim();
if (strPostMessage.length() == 0) {
Toast.makeText(appContext, "Type message.", Toast.LENGTH_LONG)
.show();
} else {
messageType = "text";
}
}
// on this button click i want to post images to server
else if (v.getId() == R.id.imageviewCamera) {
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, 1);
} else if (v.getId() == R.id.imageviewGallery) {
/*
* Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
* intent.setType("image/*"); startActivityForResult(intent, 2);
*/
selectImageFromGallery();
} else if (v.getId() == R.id.txtAudioSong) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
intent.setType("audio/*");
startActivityForResult(intent, 3);
} else if (v.getId() == R.id.txtVedioSong) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
intent.setType("video/*");
startActivityForResult(intent, 4);
}
}
public String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null,
null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
public void selectImageFromGallery() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"),
PICK_IMAGE);
}
public void decodeFile(String filePath) {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
bitmap = BitmapFactory.decodeFile(filePath, o2);
if (bitmap != null) {
new ImageUploadTask().execute();
}
}
private Bitmap bitmap;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.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 picturePath = cursor.getString(columnIndex);
cursor.close();
decodeFile(picturePath);
}
}
class ImageUploadTask extends AsyncTask<Void, Void, String> {
// private String webAddressToPost = "http://your-website-here.com";
// private ProgressDialog dialog;
private ProgressDialog dialog = new ProgressDialog(
SendPostActivity.this);
#Override
protected void onPreExecute() {
dialog.setMessage("Uploading...");
dialog.show();
}
#Override
protected String doInBackground(Void... params) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(Constant.serverUrl
+ "PostComment");
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
String file = Base64.encodeToString(data, Base64.DEFAULT);
entity.addPart("file", new StringBody(file));
entity.addPart(
"user_id",
new StringBody(Utility.getSharedPreferences(appContext,
Constant.USER_ID)));
entity.addPart(
"msg_id",
new StringBody(Utility.getSharedPreferences(appContext,
Constant.MESSAGE_ID)));
entity.addPart("type", new StringBody("image"));
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost,
localContext);
BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String sResponse = reader.readLine();
if (response != null) {
finalImagePath = sResponse;
}
return sResponse;
} catch (Exception e) {
// something went wrong. connection with the server error
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
Toast.makeText(getApplicationContext(), "file uploaded",
Toast.LENGTH_LONG).show();
System.out
.println("file is uploaded ////////////" + finalImagePath);
}
} // asyntask class ends
} // final class ends
Here is my server api method:
function PostComment()
{
$obj = new funcs_code();
$obj->connection();
$output = "";
$uid = mysql_real_escape_string($_REQUEST['user_id']);
$mid = mysql_real_escape_string($_REQUEST['msg_id']);
$comm = "";
$type = "text";
if(isset($_REQUEST['type']))
{
$type = mysql_real_escape_string($_REQUEST['type']);
}
if(isset($_REQUEST['comment']))
{
$comm = mysql_real_escape_string($_REQUEST['comment']);
}
$sql = "SELECT * FROM `users` WHERE user_id = '$uid'";
$res = mysql_query($sql);
if(mysql_num_rows($res)==1)
{
$row = mysql_fetch_assoc($res);
$sql1 = "SELECT * FROM `messages` WHERE msg_id = '$mid'";
$res1 = mysql_query($sql1);
if(mysql_num_rows($res1)==1)
{
$row1 = mysql_fetch_assoc($res1);
if($row['group_id'] == $row1['groupId'])
{
$status = 1; // 1 for comment
$fileName = "";
if(isset($_FILES['file']) && is_array($_FILES['file']))
{
$allowedExts = array("jpeg", "jpg", "mp3", "mp4", "3gp");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
//
//Check File Extension & Size UPTO 5 MB
//
if (( $_FILES["file"]["type"] == "image/jpg" || $_FILES["file"]["type"] == "image/jpeg" || $_FILES["file"]["type"] == "audio/mpeg"
|| $_FILES["file"]["type"] == "video/3gpp" || $_FILES["fiile"]["type"] == "video/mp4" ) && $_FILES["file"]["size"] < 5242880 && in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
//echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
$output = array('status' => 'error','message' => $_FILES["file"]["error"]);
header('content-type: application/json');
echo json_encode($output);
exit;
}
else
{
$fileName = time().".$extension";
move_uploaded_file($_FILES["file"]["tmp_name"], "uploads/". $fileName);
$fileName = '/uploads/'.$fileName;
}
}
else
{
$output = array('status' => 'error','message' => "Invalid_File");
header('content-type: application/json');
echo json_encode($output);
exit;
}
if($fileName != '' && $type != 'text')
{
$comm = $fileName;
}
}
//
//Below Condition Used to check, If uploading any media and File not Uploaded
//
if($type != 'text' && $fileName == ""){
$output = array('status' => 'error','message' => "Please, Specify valid Parameter for file");
header('content-type: application/json');
echo json_encode($output);
exit;
}
//
//In Any Case Comment can not be left blank
//
if($comm != "")
{
$sq = "INSERT INTO `user_comment`(`user_id`,`msg_id`,`type`,`comment`,`status`) VALUES('$uid','$mid','$type','$comm','$status')";
if(mysql_query($sq))
$output = array('status' => 'success','message' => "Comment_Success");
else
$output = array('status' => 'error','message' => "Comment_Fail");
}else{
$output = array('status' => 'error','message' => "Comment Can not be blank");
header('content-type: application/json');
echo json_encode($output);
exit;
}
///////////////////////////
}// group
else
{
//$output = 'user_group not match';
$output = array('status' => 'error','message' => "User_group_Not_match");
}
}
else
{
//$output = 'invalid msg_id';
$output = array('status' => 'error','message' => "Invalid_Msg_id");
}
}
else
{
//$output = "invalid user_id";
$output = array('status' => 'error','message' => "Invalid_User");
}
header('content-type: application/json');
echo json_encode($output);
}
The type is wrong, should be image/jpeg in this line:
entity.addPart("type", new StringBody("image"));
Also, you are sending your File as a Base 64 encoded string?? Are you sure the php code handles that? Usually you are supposed to use FileBody with the file directly, but you can use a ContentBody for byte arrays.
Edit
This is how I upload a file with a ByteArrayOutputStream
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
ContentBody contentPart = new ByteArrayBody(bos.toByteArray(), "image/jpeg", "file.jpg");
mpEntity.addPart("file", contentPart);
This is how you would do it with a FileBody
File f = ....
mpEntity.addPart("file", new FileBody(f));
From your "Server api method"
if($type != 'text' && $fileName == ""){
$output = array('status' => 'error','message' => "Please, Specify valid Parameter for file");
header('content-type: application/json');
echo json_encode($output);
exit;
}
So that means $type is not equal to 'text' and $fileName is equals to "". So, go to this line:
Change this:
$fileName = time().".$extension";
Into this:
$fileName = time().'.'.$extension";
Then let me know what happened.
Hi every body i want store byte format of image in my database from url. I am using this code
URL url = new
URL("http://images.11bestbuy.com/images/small_17385013870957.jpg");
InputStream anyfile = url.openStream();
But it is showing error for me.
You can decode a Bitmap and then convert it to a byte array:
public byte[] downloadImage() throws Exception{
URL url = new URL("http://images.11bestbuy.com/images/small_17385013870957.jpg");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setReadTimeout(10000);
con.setConnectTimeout(10000);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
Bitmap b = BitmapFactory.decodeStream(con.getInputStream());
b.compress(Bitmap.CompressFormat.JPEG,100,bos);
} finally {
con.disconnect();
}
return bos.toByteArray();
}
You can store byte array in BLOB type record of a SQLite database.
Try this it is working for me
static private Bitmap downloadBitmap(String url) throws IOException {
HttpUriRequest request = new HttpGet(url);
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
System.out.println("kjklcmklxc");
HttpEntity entity = response.getEntity();
byte[] bytes = EntityUtils.toByteArray(entity);
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0,
bytes.length);
bitmap.compress(Bitmap.CompressFormat.JPEG, 40, byt_aary_outpt_strm);
dh.delete(DatabaseHelper.Image_handler, null, null);
bitmapdata = byt_aary_outpt_strm.toByteArray();
System.out.println("bitmap of image converted image");
for(int i =0 ; i<bitmapdata.length;i++){
convert_save_byte_str = convert_save_byte_str+bitmapdata[i];
}
System.out.println("njdsfnh"+convert_save_byte_str);
ContentValues userdetailValues = new ContentValues();
userdetailValues.put("image_byte", convert_save_byte_str);
System.out.println("between put and insert");
dh.insert(DatabaseHelper.Image_handler, null, userdetailValues);
cursor = dh.rawQuery("SELECT _id, image_byte FROM image_database",null);
int i=0;
if (cursor.moveToFirst()) {
do {
// get the data into array,or class variable
bb = cursor.getBlob(cursor.getColumnIndex(DatabaseHelper.Image_handeler_column));
//System.out.println("productid"+data);
//intent.putExtra("product_id", data);
System.out.print("bytengkfgkjgk"+bb[i]);
i++;
} while (cursor.moveToNext());
}
return bitmap;
} else {
throw new IOException("Download failed, HTTP response code "
+ statusCode + " - " + statusLine.getReasonPhrase());
}
}
I am sending Images and Text to a PHP webservice using the following code.
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(URL);
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 75, bos);
byte[] data = bos.toByteArray();
entity.addPart("files[]",
new ByteArrayBody(data, "myImage.jpg"));
entity.addPart("message0", new StringBody(caption.getText()
.toString()));
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost,
localContext);
BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String sResponse = reader.readLine();
return sResponse;
} catch (Exception e) {
if (dialog.isShowing())
dialog.dismiss();
Toast.makeText(ImageUpload.this, e.getMessage(),
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
return null;
}
}
It works perfectly. But this is only for one image. I want to send 5 images.
Example: Image1 - Text1
Image2 - Text2 etc..
So I am confused about how to store 5 images one by one and then on button click, send these images and text associated with them to the server.
I am getting images from the phone's camera.
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, "Select Picture"),
PICK_IMAGE);
public void onActivityResult_photo(int requestCode, int resultCode,
Intent data) {
// TODO Auto-generated method stub
if (resultCode == RESULT_OK) {
if (data != null) {
mImageCaptureUri = data.getData();
display(mImageCaptureUri);
} else {
Toast.makeText(CustomTabActivity.mTabHost.getContext(),
"No photo selected..", Toast.LENGTH_SHORT).show();
}
}
}
private String display(Uri mImageCaptureUri2) {
// TODO Auto-generated method stub
String base64string = null;
try {
if (mImageCaptureUri2 != null) {
System.gc();
selectedImagePath = getPath(mImageCaptureUri2);
File filenew = new File(selectedImagePath);
int file_size = Integer.parseInt(String.valueOf(filenew
.length() / 1024));
if (file_size <= 10000) {
PD1 = ProgressDialog.show(
CustomTabActivity.mTabHost.getContext(), "",
"Loading...");
Handler refresh = new Handler(Looper.getMainLooper());
refresh.post(new Runnable() {
public void run() {
PD1.setCancelable(true);
Bitmap newbitmap;
newbitmap = decodeFile(selectedImagePath);
ByteArrayOutputStream bs = new ByteArrayOutputStream();
newbitmap.compress(Bitmap.CompressFormat.PNG, 50,
bs);
img.setVisibility(View.VISIBLE);
img.setImageBitmap(newbitmap);
byte[] abc = bitmapToByteArray(newbitmap);
if (txt_phototext.getText().toString().equals("")) {
submit.put(abc, "");
} else {
submit.put(abc, txt_phototext.getText()
.toString());
// executeMultipartPost();
}
PD1.dismiss();
}
});
} else {
AlertDialog.Builder alertbox = new AlertDialog.Builder(
CustomTabActivity.mTabHost.getContext());
alertbox.setMessage("Take Image Size Less than 10 MB");
alertbox.setNeutralButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0,
int arg1) {
finish();
}
});
alertbox.show();
}
} else {
System.out.println("===============NULL========");
}
} catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
}
return base64string;
}
static Bitmap decodeFile(String str) {
try {
// decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(str), null, o);
// Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE = 70;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale++;
}
// decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(str), null,
o2);
} catch (FileNotFoundException e) {
}
return null;
}
public static byte[] bitmapToByteArray(Bitmap bitmap) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0 /* ignored for PNG */, bos);
byte[] bitmapdata = bos.toByteArray();
return bitmapdata;
}
And make sure that your directory or folder in server is Executable, Writable and Readable. I had this as the major problem. This is called 777 permission.. Believe me, this is as important as other things to consider.
For full detail please have a look on my post Click here
its quite difficult to send multiple images to server using MultipartEntity. I did search for this but didn't find any right solution then i made my own way to send multiple images to server
, here i send array of selected paths to asynctask and in asynctask i sent images to server
Calling Asysnctask Function-
new Upload_Multiple.excute(Array_of_Path[]))
Private class Upload_Multiple_img extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
protected String doInBackground(String... paths_array) {
String data = "";
for (int i = 0; i < paths_array.length; i++) {
// get_Picture_bitmap() returns bitmap by passing path of image
// get_Picture_bitmap() is mentioned below.
Bitmap bitmap = get_Picture_bitmap(paths_array[i]);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
InputStream in = new ByteArrayInputStream(stream.toByteArray()); // convert
DefaultHttpClient httpclient = new DefaultHttpClient();
String server_funtion_url="...serveraddres"+funtion_at_server"";
HttpPost httppost = new HttpPost(server_funtion_url); // server
MultipartEntity reqEntity = new MultipartEntity();
obj_SP = ImagePicker.this.getSharedPreferences("Eperty", 0);
String id_prop = obj_SP.getString("new_prop_id", "");
String Image_Name =
+ String.valueOf(System.currentTimeMillis()) + ".jpg";
// image is a key which is used at server end to get this
reqEntity.addPart("image", Image_Name, in);
httppost.setEntity(reqEntity);
HttpResponse response = null;
try {
response = httpclient.execute(httppost);
data = EntityUtils.toString(response.getEntity());
System.out.println("FFFF== " + data);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return data;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
ConstantData.ToastAlert(ImagePicker.this,
"Images Uploaded successfully");
}
}
//);
For compressing the images and getting bitmap for i made below funtion*
public Bitmap get_Picture_bitmap(String imagePath) {
long size_file = getFileSize(new File(imagePath));
size_file = (size_file) / 1000;// in Kb now
int ample_size = 1;
if (size_file <= 250) {
System.out.println("SSSSS1111= " + size_file);
ample_size = 2;
} else if (size_file > 251 && size_file < 1500) {
System.out.println("SSSSS2222= " + size_file);
ample_size = 4;
} else if (size_file >= 1500 && size_file < 3000) {
System.out.println("SSSSS3333= " + size_file);
ample_size = 8;
} else if (size_file >= 3000 && size_file <= 4500) {
System.out.println("SSSSS4444= " + size_file);
ample_size = 12;
} else if (size_file >= 4500) {
System.out.println("SSSSS4444= " + size_file);
ample_size = 16;
}
Bitmap bitmap = null;
BitmapFactory.Options bitoption = new BitmapFactory.Options();
bitoption.inSampleSize = ample_size;
Bitmap bitmapPhoto = BitmapFactory.decodeFile(imagePath, bitoption);
ExifInterface exif = null;
try {
exif = new ExifInterface(imagePath);
} catch (IOException e) {
// Auto-generated catch block
e.printStackTrace();
}
int orientation = exif
.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
Matrix matrix = new Matrix();
if ((orientation == 3)) {
matrix.postRotate(180);
bitmap = Bitmap.createBitmap(bitmapPhoto, 0, 0,
bitmapPhoto.getWidth(), bitmapPhoto.getHeight(), matrix,
true);
} else if (orientation == 6) {
matrix.postRotate(90);
bitmap = Bitmap.createBitmap(bitmapPhoto, 0, 0,
bitmapPhoto.getWidth(), bitmapPhoto.getHeight(), matrix,
true);
} else if (orientation == 8) {
matrix.postRotate(270);
bitmap = Bitmap.createBitmap(bitmapPhoto, 0, 0,
bitmapPhoto.getWidth(), bitmapPhoto.getHeight(), matrix,
true);
} else {
matrix.postRotate(0);
bitmap = Bitmap.createBitmap(bitmapPhoto, 0, 0,
bitmapPhoto.getWidth(), bitmapPhoto.getHeight(), matrix,
true);
}
return bitmap;
}
**
Server end Code *
$target_dir = "../webadmin/user_image/";
$target_dir = $target_dir . basename($_FILES["user_img"]["name"]);
if(move_uploaded_file($_FILES["image"]["tmp_name"], $target_dir))
{
$msg = "The file ". basename($result[0]). " has been uploaded.";
$send_arr['success'] = 1;
$send_arr['message'] = $msg;
echo json_encode($send_arr);
}
else
{
$msg = "Sorry, there was an error uploading your file.";
$send_arr['success'] = 0;
$send_arr['message'] = $msg;
echo json_encode($send_arr);
}
Why you can't just create array of json object of your images to base64 and post to server and at your server api read those images convert to byte and use as image.
Check my answe and try to implement.
In Android how to post data to webservice which is created in WCF?
And the images you are getting from camera store them in uri in sdcard and letter read them. You can assign image name sequntialy. And read them from uri.
Try increasing the post_max_size of your php.ini file in WAMP server
Please find the below method...here i m sending mutiple image file using AQUERY. The best lib to perform all background network related task.(Like AJAX).
https://code.google.com/p/android-query/
public void uploadImageFile( String filePath,
String message) {
Context context = ApplicationContextProvider.getContext();
String url = SERVER_URL + "/user/uploadImageFile";
try {
Toast.makeText(context, "Uploading...", Toast.LENGTH_SHORT)
.show();
String compressedFile = CommonUtilities.compressImage(filePath,
context);
Map<String, Object> params = new HashMap<String, Object>();
File imageFile = new File(compressedFile);
byte[] imageBytes1 = FileUtils.readFileToByteArray(imageFile);
params.put("imageBytes", imageBytes1);
params.put("message",URLEncoder.encode(message, "UTF-8"));
AQuery aq = new AQuery(context);
aq.ajax(url, params, JSONObject.class,
new AjaxCallback<JSONObject>() {
#Override
public void callback(String url, JSONObject json,
AjaxStatus status) {
Toast.makeText(
ApplicationContextProvider.getContext(),
"Uploaded successfully",
Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT)
.show();
}
}