Minggu, 19 Mei 2019

Detail galeri



galeridetail.xml

<?xml version="1.0" encoding="utf-8"?><ScrollView xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:background="#fff"  >

    <LinearLayout        android:layout_width="fill_parent"        android:layout_height="fill_parent"        android:orientation="vertical"        android:padding="6dip" >
        <TextView            android:id="@+id/txtMarquee"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text=""            android:textSize="14sp"            android:typeface="sans"            android:textColor="#ffffff"            android:background="#000000"            android:singleLine="true"            android:ellipsize="marquee"            android:marqueeRepeatLimit="marquee_forever">
        </TextView>

        <ImageView            android:id="@+id/myGambar"            android:gravity="center"            android:layout_width="match_parent"            android:layout_height="match_parent"            android:layout_centerHorizontal="true"            android:layout_centerVertical="true"            android:src="@drawable/gallery" />
             />

        <ZoomControls            android:layout_marginTop="10dip"            android:id="@+id/simpleZoomControl"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:background="#000" />


        <TextView            android:id="@+id/title"            android:layout_width="fill_parent"            android:layout_marginTop="6dip"            android:layout_height="wrap_content"            android:text="Judul"            android:textColor="#000000"            android:textSize="20sp"            android:textStyle="bold" />

        <TextView            android:id="@+id/title2"            android:layout_width="fill_parent"            android:layout_marginTop="6dip"            android:layout_height="wrap_content"            android:text="Keterangan"            android:textColor="#000000"            android:textSize="20sp" />

        <TextView            android:id="@+id/title3"            android:layout_width="fill_parent"            android:layout_marginTop="6dip"            android:layout_height="wrap_content"            android:text="Tgl"            android:textColor="#000000"            android:textSize="20sp" />

        <TextView            android:id="@+id/title4"            android:layout_width="fill_parent"            android:layout_height="wrap_content"            android:layout_marginTop="6dip"            android:text="Pengriim"            android:textColor="#000000"            android:textSize="20sp"/>

        <TableRow            android:id="@+id/TableRow02"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_gravity="center">

            <Button                android:id="@+id/btnShare"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:text="Share"                android:textColor="#000000"                android:textStyle="bold" />

            <Button                android:id="@+id/btnsave"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:text="Download"                android:textColor="#000000"                android:textStyle="bold" />

        </TableRow>
        <TextView
        android:layout_width="fill_parent"        android:layout_marginTop="6dip"        android:layout_height="wrap_content"        android:text=""        android:textColor="#000000"        android:textSize="20sp"        android:textStyle="bold" />
    </LinearLayout>

</ScrollView>


package com.kriptograph.mygaleri;

import android.Manifest;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ZoomControls;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Calendar;

public class DetailGaleri extends AppCompatActivity {
    JSONParser jsonParser = new JSONParser();

    String tkode="",tnama="",tmail="",thp="",tlati="",tlongi="",talamat="",tangkatan="",tstatus="",tgambar="",waktu="";
    String skodelogin="",snamalogin="",smaillogin="";
    String myLati="-6.352953";
    String myLongi="106.831389";
    String myPosisi="UI";
    ZoomControls simpleZoomControls;
    ImageView myGambar;

String ip="";
    private ProgressDialog pDialog;
    JSONParser jParser = new JSONParser();
    String title,title2, title3, title4, gambar;

    String currentImage = "";

    private static final int MY_PERMISSION_REQUEST = 1;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.galeridetail);
        myGambar=(ImageView) findViewById(R.id.myGambar);

        simpleZoomControls = (ZoomControls) findViewById(R.id.simpleZoomControl);
        simpleZoomControls.setOnZoomInClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
                float x=simpleZoomControls.getScaleX();
                float y=simpleZoomControls.getScaleY();
                myGambar.setScaleX((float) (x+1));
                myGambar.setScaleY((float) (y+1));
            }
        });

        simpleZoomControls.setOnZoomOutClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
                float x=simpleZoomControls.getScaleX();
                float y=simpleZoomControls.getScaleY();
                myGambar.setScaleX((float) (x-1));
                myGambar.setScaleY((float) (y-1));
            }
        });

        //meminta izin penyimpanan        if (ContextCompat.checkSelfPermission(DetailGaleri.this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(DetailGaleri.this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                ActivityCompat.requestPermissions(DetailGaleri.this,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSION_REQUEST);
            } else {
                ActivityCompat.requestPermissions(DetailGaleri.this,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSION_REQUEST);
            }
        } else {
            //DO NOTHING        }

        ip=jParser.getIP();

         title = getIntent().getStringExtra("title");
      
        //int gb= getIntent().getIntExtra("gambar",R.drawable.ic_produk);        //Bitmap bitmap = getIntent().getParcelableExtra("image");
        String arUrlFoto=ip+"ypathfile/"+gambar;
        new DownloadImageTask(myGambar).execute(arUrlFoto);


        Button    btnShare=(Button)findViewById(R.id.btnShare);
        btnShare.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {
                Intent sharingIntent = new Intent(Intent.ACTION_SEND);
                sharingIntent.setType("text/plain");
                sharingIntent.putExtra(Intent.EXTRA_TEXT, "Judul :"+title+"\n\nKet :"+title3+"\n\nWaktu :"+waktu+"\n\nPengirim :"+title4);
                sharingIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
                startActivity(Intent.createChooser(sharingIntent, "Share using"));

            }});


        Button    btnsave=(Button)findViewById(R.id.btnsave);btnsave.setText("Download");
        btnsave.setVisibility(View.VISIBLE);
        btnsave.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {
                savepicture();
            }});
        callMarquee();
    }




    private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
        ImageView bmImage;

        public DownloadImageTask(ImageView bmImage) {
            this.bmImage = bmImage;
        }

        protected Bitmap doInBackground(String... urls) {
            String urldisplay = urls[0];
            Bitmap mIcon11 = null;
            try {
                InputStream in = new java.net.URL(urldisplay).openStream();
                mIcon11 = BitmapFactory.decodeStream(in);
            }
            catch (Exception e) {
                Log.e("Error", e.getMessage());e.printStackTrace();}
            return mIcon11;
        }

        protected void onPostExecute(Bitmap result) {bmImage.setImageBitmap(result); }
    }


    void callMarquee(){
        Calendar cal = Calendar.getInstance();
        int jam = cal.get(Calendar.HOUR);
        int menit= cal.get(Calendar.MINUTE);
        int detik= cal.get(Calendar.SECOND);

        int tgl= cal.get(Calendar.DATE);
        int bln= cal.get(Calendar.MONTH)+1;
        int thn= cal.get(Calendar.YEAR);

        String stgl= String.valueOf(tgl)+"-"+ String.valueOf(bln)+"-"+ String.valueOf(thn);
        String sjam= String.valueOf(jam)+":"+ String.valueOf(menit)+":"+ String.valueOf(detik);

        TextView txtMarquee=(TextView)findViewById(R.id.txtMarquee);
        txtMarquee.setSelected(true);
        String kata=jsonParser.getNama()+stgl+"/"+sjam+" #";
        String kalimat= String.format("%1$s", TextUtils.htmlEncode(kata));
        txtMarquee.setText(Html.fromHtml(kalimat+kalimat+kalimat));
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    public void savepicture() {
        AlertDialog.Builder ad = new AlertDialog.Builder(DetailGaleri.this);
        ad.setTitle("Save Picture");
        ad.setMessage(title+" \n"+title3+"\n"+title4);

        ad.setPositiveButton("Save", new DialogInterface.OnClickListener() {
            @Override            public void onClick(DialogInterface dialog, int which) {

                View content = findViewById(R.id.myGambar);
                Bitmap bitmap = getScreenShot(content);
//                currentImage = "image" + System.currentTimeMillis() + ".jpg";                currentImage = title+" \n"+title3+"\n"+title4+".jpg";
                store(bitmap, currentImage);
//                b_share.setEnabled(true);               // finish();            }
        });
        ad.setNegativeButton("Cancle", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface arg0, int arg1) {
            }
        });
        ad.show();
    }

    private static Bitmap getScreenShot(View view) {
        view.setDrawingCacheEnabled(true);
        Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
        view.setDrawingCacheEnabled(false);
        return bitmap;
    }

    private void store(Bitmap bm, String fileName) {
        String dirPath = Environment.getExternalStorageDirectory().getAbsolutePath()+"/FILEPROJEK";
        File dir = new File(dirPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File file = new File(dirPath, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bm.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
            Toast.makeText(this, "Saved to "+dirPath +"..!", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();

        }
    }



    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, 1, 0, "Profile");
        menu.add(0, 2, 0, "Call");
        menu.add(0, 3, 0, "Mail");
        menu.add(0, 4, 0, "Message");
        menu.add(0, 5, 0, "Location");
        menu.add(0, 6, 0, "Direction");
        menu.add(0, 7, 0, "Activity");
        menu.add(0, 8, 0, "Back");
        return true;
    }

    final Context c = this;
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case 1:
                Intent i1 = new Intent(getApplicationContext(), Galeri.class);
                i1.putExtra("pk",tkode);
                startActivityForResult(i1, 100);
                return true;
            case 2:
                String toDial="tel:"+thp;
                startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(toDial)));
                return true;
            case 3:
                //Mail                LayoutInflater layoutInflaterAndroid = LayoutInflater.from(c);
                View mView = layoutInflaterAndroid.inflate(R.layout.user_input_dialog_box, null);
                AlertDialog.Builder alertDialogBuilderUserInput = new AlertDialog.Builder(c);
                alertDialogBuilderUserInput.setView(mView);

                final EditText userInputDialogEditText = (EditText) mView.findViewById(R.id.userInputDialog);
                alertDialogBuilderUserInput
                        .setCancelable(false)
                        .setPositiveButton("Send", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialogBox, int id) {

                                //========================
                                String pesan=userInputDialogEditText.getText().toString();
                                if(pesan.length()>0) {
                                    String to = tmail;
                                    String subject = "Kirim Pesan Via APP-M8 ";
                                    String message = pesan + "\nTertanda:" + snamalogin + " /" + skodelogin + " (" + smaillogin + ")";

                                    Intent email = new Intent(Intent.ACTION_SEND);
                                    email.putExtra(Intent.EXTRA_EMAIL, new String[]{to});
                                    //email.putExtra(Intent.EXTRA_CC, new String[]{ to});                                    //email.putExtra(Intent.EXTRA_BCC, new String[]{to});                                    email.putExtra(Intent.EXTRA_SUBJECT, subject);
                                    email.putExtra(Intent.EXTRA_TEXT, message);

                                    //need this to prompts email client only                                    email.setType("message/rfc822");

                                    startActivity(Intent.createChooser(email, "Fr:" + smaillogin));
                                    new AlertDialog.Builder(DetailGaleri.this)
                                            .setTitle("Mail to "+tnama)
                                            .setMessage("Sukses Kirim mail ke "+tmail+" /"+tnama+" ("+tkode+")")
                                            .setNeutralButton("OK", new DialogInterface.OnClickListener() {
                                                public void onClick(DialogInterface dlg, int sumthin) {
                                                    finish();
                                                }}).show();
                                }
                                else{
                                    LayoutInflater inflater = getLayoutInflater();
                                    View layout = inflater.inflate(R.layout.custom_toast,(ViewGroup) findViewById(R.id.custom_toast_layout_id));
                                    ImageView image = (ImageView) layout.findViewById(R.id.image);
                                    image.setImageResource(R.drawable.logochat);
                                    TextView text = (TextView) layout.findViewById(R.id.text);
                                    text.setText("Silakan isi pesan Mail Anda");

                                    Toast toast = new Toast(getApplicationContext());
                                    toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
                                    toast.setDuration(Toast.LENGTH_LONG);
                                    toast.setView(layout);
                                    toast.show();
                                }
                                //========================                            }
                        })

                        .setNegativeButton("Cancel",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialogBox, int id) {
                                        dialogBox.cancel();
                                    }
                                });

                AlertDialog alertDialogAndroid = alertDialogBuilderUserInput.create();
                alertDialogAndroid.show();


                return true;
            case 4:
                //Inbox message                Intent i2 = new Intent(getApplicationContext(), Galeri.class);
                i2.putExtra("tkode",tkode);
                i2.putExtra("tnama",tnama);
                startActivityForResult(i2, 100);
                return true;
            case 5:
                //Location                Intent i3 = new Intent(getApplicationContext(), Galeri.class);
                i3.putExtra("tkode",tkode);
                i3.putExtra("tnama",tnama);
                i3.putExtra("myLati",myLati);
                i3.putExtra("myLongi",myLongi);
                i3.putExtra("myPosisi",myPosisi);
                i3.putExtra("myLati2",tlati);
                i3.putExtra("myLongi2",tlongi);
                i3.putExtra("myPosisi2",talamat);

                startActivityForResult(i3, 100);
                return true;
            case 6:
                //direction                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://maps.google.com/maps?saddr="+myLati+","+myLongi+"&daddr="+tlati+","+tlongi));
                startActivity(intent);
                return true;
            case 7:
                //activity                Intent i4 = new Intent(getApplicationContext(), Galeri.class);
                i4.putExtra("tkode",tkode);
                i4.putExtra("tnama",tnama);
                i4.putExtra("tangkatan",tangkatan);
                i4.putExtra("tstatus",tstatus);
                i4.putExtra("tgambar",tgambar);
                startActivityForResult(i4, 100);
                return true;
            case 8:
                //back                finish();
                return true;

        }
        return false;
    }
}


user_input_dialog_box.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:id="@+id/custom_dialog_layout_design_user_input"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    android:padding="16dp">

    <TextView        android:id="@+id/dialogTitle"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Send Mail"        android:textAppearance="?android:attr/textAppearanceLarge" />

    <EditText        android:id="@+id/userInputDialog"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:hint="Pesan Mail"        android:inputType="text" />
</LinearLayout>



custom_toast.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:id="@+id/custom_toast_layout_id"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:background="#FFF"    android:orientation="horizontal"    android:padding="5dp" >

    <ImageView        android:id="@+id/image"        android:layout_width="wrap_content"        android:layout_height="fill_parent"        android:layout_marginRight="5dp" />

    <TextView        android:id="@+id/text"        android:layout_width="wrap_content"        android:layout_height="fill_parent"        android:textColor="#000" />

</LinearLayout>



UPLOAD IMAGE



<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    >

    <ImageView        android:src="@drawable/gallery2"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_weight="1"        android:id="@+id/imageView" />

    <TextView        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="Judul Foto"        android:textColor="#000000"        android:textSize="20sp"        android:textStyle="bold"/>

    <!--  telepon TextField -->    <EditText        android:id="@+id/txtjudul"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:textColor="#000000" />


    <TextView        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="Info Tambahan"        android:textColor="#000000"        android:textSize="20sp"        android:textStyle="bold"/>

    <!--  telepon TextField -->    <EditText        android:id="@+id/txtketerangan"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:textColor="#000000" />

    <Button        android:textColor="#ffffff"        android:textStyle="bold"        android:background="#ff0f0f"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="UPLOAD NOW"        android:id="@+id/uploadButton"        />

    <Button        android:textStyle="bold"        android:background="#00d000"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="Image Galeri"        android:id="@+id/btnpilih"        />


    <Button        android:textStyle="bold"        android:background="#a0a000"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="Image Camera"        android:id="@+id/btncamera"        />



    <TextView        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text=""        android:id="@+id/messageText"        android:textColor="#000000"        android:textStyle="bold"        />
</LinearLayout>


++++++++++++++
package com.kriptograph.mygaleri;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;


public class UploadToServer extends Activity {
    String myip="";
    JSONParser jsonParser = new JSONParser();
    EditText txtjudul,txtketerangan;

    private static final int PICK_IMAGE = 1;
    private static final int PICK_Camera_IMAGE = 2;
    private ImageView imgView;
    private Button upload,cancel;
    private Bitmap bitmap;
    Uri imageUri;
    MediaPlayer mp=new MediaPlayer();

    String kode_anggota,nama_anggota,email;

    String URL="";
    TextView messageText;
    Button uploadButton,btnpilih,btncamera;
    int serverResponseCode = 0;
    ProgressDialog dialog = null;

    String upLoadServerUri = null;

    /**********  File Path *************/   String uploadFilePath = "/mnt/sdcard/";
    String uploadFileName = "m8album.png";

    @Override    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.uploadserver);

        SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(UploadToServer.this);
        Boolean Registered = sharedPref.getBoolean("Registered", false);
        if (!Registered) {
            finish();
        } else {
            kode_anggota = sharedPref.getString("kode_anggota", "");
            nama_anggota = sharedPref.getString("nama_anggota", "");
            email = sharedPref.getString("email", "");
        }


        txtjudul= (EditText) findViewById(R.id.txtjudul);
        txtketerangan = (EditText) findViewById(R.id.txtketerangan);

        imgView = (ImageView) findViewById(R.id.imageView);
        uploadButton = (Button)findViewById(R.id.uploadButton);
        messageText  = (TextView)findViewById(R.id.messageText);

        btnpilih = (Button)findViewById(R.id.btnpilih);
        btncamera = (Button)findViewById(R.id.btncamera);

        messageText.setText(uploadFilePath+"/"+uploadFileName+"'");

        URL=jsonParser.getIP()+"uploadserver.php";
        upLoadServerUri =   URL;
        uploadButton.setOnClickListener(new OnClickListener() {
            @Override            public void onClick(View v) {

                String judul=txtjudul.getText().toString();
                if(judul.length()>0) {
                    dialog = ProgressDialog.show(UploadToServer.this, "", "Uploading file...", true);
                    new Thread(new Runnable() {
                        public void run() {
                            runOnUiThread(new Runnable() {
                                public void run() {
                                    messageText.setText("Uploading Started.....");
                                }
                            });
                            String AL = messageText.getText().toString();
                            uploadFiles(AL);
                            finish();

                        }
                    }).start();
                }
                else{
                    lengkapi();
                }
            }
        });

        btnpilih.setOnClickListener(new OnClickListener() {
            @Override            public void onClick(View v) {
                try {
                    Intent gintent = new Intent();
                    gintent.setType("image/*");
                    gintent.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(Intent.createChooser(gintent, "Select Picture"),PICK_IMAGE);
                } catch (Exception e) {
                    Toast.makeText(getApplicationContext(),
                            e.getMessage(),
                            Toast.LENGTH_LONG).show();
                    Log.e(e.getClass().getName(), e.getMessage(), e);
                }
            }
        });


        btncamera.setOnClickListener(new OnClickListener() {
            @Override            public void onClick(View v) {
                //define the file-name to save photo taken by Camera activity                String fileName = "uploadFile.jpg";
                //create parameters for Intent with filename                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.TITLE, fileName);
                values.put(MediaStore.Images.Media.DESCRIPTION,"Image captured by camera");
                //imageUri is the current activity attribute, define and save it for later usage (also in onSaveInstanceState)                imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
                //create new Intent                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
                startActivityForResult(intent, PICK_Camera_IMAGE);
            }
        });


        uploadButton.setVisibility(View.GONE);

    }
    public void lengkapi() {
        new AlertDialog.Builder(this)
                .setTitle("Lengkapi Judul")
                .setMessage("Yth "+nama_anggota+", Silakan lengkapi Judul Galeri Anda")
                .setNeutralButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dlg, int sumthin) {
                    }
                })
                .show();
    }
    public int uploadFiles(String sourceFileUri) {
        String fileName = sourceFileUri;
        uploadFileName=fileName;
        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        String lineEnd = "\r\n";
        String boundary = "*****";

        File sourceFile = new File(sourceFileUri);

        if (!sourceFile.isFile()) {
            dialog.dismiss();
            Log.e("uploadFile", "Source File not exist :"  +uploadFilePath + "" + uploadFileName);
            runOnUiThread(new Runnable() {
                public void run() {
                    messageText.setText("File not exist :"+uploadFilePath + "" + uploadFileName);
                }
            });

            return 0;

        }
        else        {
            try {
                String judul=txtjudul.getText().toString();
                String keterangan=txtketerangan.getText().toString();

                URL url = new URL(upLoadServerUri);

                conn = (HttpURLConnection) url.openConnection();
                conn.setDoInput(true); // Allow Inputs                conn.setDoOutput(true); // Allow Outputs                conn.setUseCaches(false); // Don't use a Cached Copy                conn.setRequestMethod("POST");

                conn.setRequestProperty("Connection", "Keep-Alive");
                conn.setRequestProperty("ENCTYPE", "multipart/form-data");
                conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

                //fileName=/storage/sdcard0/WhatsApp/Media/WhatsApp Documents/Streaming.jpg
                dos = new DataOutputStream(conn.getOutputStream());
                addSring("kode_anggota",kode_anggota,dos,lineEnd);
                addSring("judul",judul,dos,lineEnd);
                addSring("keterangan",keterangan,dos,lineEnd);
                addGambar("uploaded_file",fileName,dos,lineEnd);

                serverResponseCode = conn.getResponseCode();
                String serverResponseMessage = conn.getResponseMessage();
                Log.i("uploadFile", "HTTP Response is : "   + serverResponseMessage + ": " + serverResponseCode);


                if(serverResponseCode == 200){
                    runOnUiThread(new Runnable() {
                        public void run() {
                            String msg = "File Upload Completed :"+uploadFileName;
                            messageText.setText(msg);
                            Toast.makeText(UploadToServer.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
                dos.flush();
                dos.close();
                uploadButton.setVisibility(View.GONE);
                txtjudul.setText("");
                txtketerangan.setText("");
            } catch (MalformedURLException ex) {

                dialog.dismiss();
                ex.printStackTrace();

                runOnUiThread(new Runnable() {
                    public void run() {
                        messageText.setText("Fail Upload");
                       //Toast.makeText(UploadToServer.this, "MalformedURLException", Toast.LENGTH_SHORT).show();                    }
                });

            } catch (Exception e) {

                dialog.dismiss();
                e.printStackTrace();

                runOnUiThread(new Runnable() {
                    public void run() {
                        messageText.setText("Fail Uploaded.. ");
                 //       Toast.makeText(UploadToServer.this, "Got Exception : see logcat ", Toast.LENGTH_SHORT).show();                    }
                });

            }
            dialog.dismiss();
            return serverResponseCode;

        } // End else block
    }

    public void addSring(String fieldName, String value,DataOutputStream request,String lineEnd)throws IOException  {
        String twoHyphens = "--";
        String boundary = "*****";
        request.writeBytes(twoHyphens + boundary + lineEnd);
        request.writeBytes("Content-Disposition: form-data; name=\"" + fieldName + "\""+ lineEnd);
        request.writeBytes("Content-Type: text/plain; charset=UTF-8" + lineEnd);
        request.writeBytes(lineEnd);
        request.writeBytes(value+ lineEnd);
        request.flush();
    }

    public void addGambar(String fieldName, String sourceFileUri,DataOutputStream request,String lineEnd)throws IOException {
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;

        String twoHyphens = "--";
        String boundary = "*****";
        request.writeBytes(twoHyphens + boundary + lineEnd);
        request.writeBytes("Content-Disposition: form-data; name=\"" +  fieldName + "\";filename=\"" + sourceFileUri + "\"" + lineEnd);
        request.writeBytes(lineEnd);

        //byte[] bytes = Files.readAllBytes(uploadFile.toPath());        //request.write(bytes);        FileInputStream fileInputStream = new FileInputStream(sourceFileUri);
        bytesAvailable = fileInputStream.available();

        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];

        // read file and write it into form...        bytesRead = fileInputStream.read(buffer, 0, bufferSize);

        while (bytesRead > 0) {
            request.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);

        }

        request.writeBytes(lineEnd);
        request.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
        fileInputStream.close();
    }

    private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException  {
        StringBuilder result = new StringBuilder();
        boolean first = true;

        for (NameValuePair pair : params)
        {
            if (first)
                first = false;
            else                result.append("&");

            result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
        }

        return result.toString();
    }


    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Uri selectedImageUri = null;
        String filePath = null;
        switch (requestCode) {
            case PICK_IMAGE:
                if (resultCode == Activity.RESULT_OK) {
                    selectedImageUri = data.getData();
                }
                break;
            case PICK_Camera_IMAGE:
                if (resultCode == RESULT_OK) {
                    //use imageUri here to access the image                    selectedImageUri = imageUri;
          /*Bitmap mPic = (Bitmap) data.getExtras().get("data");      selectedImageUri = Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(), mPic, getResources().getString(R.string.app_name), Long.toString(System.currentTimeMillis())));*/                } else if (resultCode == RESULT_CANCELED) {
                    Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT).show();
                }
                break;
        }

        if(selectedImageUri != null){
            uploadButton.setVisibility(View.VISIBLE);

            try {
                String filemanagerstring = selectedImageUri.getPath();
                String selectedImagePath = getPath(selectedImageUri);
                messageText.setText(selectedImagePath);
                if (selectedImagePath != null) {
                    filePath = selectedImagePath;
                } else if (filemanagerstring != null) {
                    filePath = filemanagerstring;
                } else {
                    Toast.makeText(getApplicationContext(), "Unknown path",  Toast.LENGTH_LONG).show();
                    Log.e("Bitmap", "Unknown path");
                }

                if (filePath != null) {
                    decodeFile(filePath);
                } else {
                    bitmap = null;
                }
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), "Internal error",  Toast.LENGTH_LONG).show();
                Log.e(e.getClass().getName(), e.getMessage(), e);
            }
        }

    }



    class ImageGalleryTask extends AsyncTask<Void, Void, String> {
        @SuppressWarnings("unused")
        @Override        protected String doInBackground(Void... unsued) {
            InputStream is;
            BitmapFactory.Options bfo;
            Bitmap bitmapOrg;
            ByteArrayOutputStream bao ;

            bfo = new BitmapFactory.Options();
            bfo.inSampleSize = 2;
            //bitmapOrg = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + "/" + customImage, bfo);
            bao = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bao);
            byte [] ba = bao.toByteArray();
//            String ba1 = Base64.encodeBytes(ba);
            String ba1 = Base64.encodeToString(ba,1);
            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("image",ba1));
            nameValuePairs.add(new BasicNameValuePair("cmd","image_android"));
            Log.v("log_tag", System.currentTimeMillis()+".jpg");
            try{
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new                        //  Here you need to put your server file address

                        HttpPost(URL);//"http://www.picsily.com/upload_photo.php");                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();
                Log.v("log_tag", "In the try Loop" );
            }catch(Exception e){
                Log.v("log_tag", "Error in http connection "+e.toString());
            }
            return "Success";
            // (null);        }

        @Override        protected void onProgressUpdate(Void... unsued) {

        }

        @Override        protected void onPostExecute(String sResponse) {
            try {
                if (dialog.isShowing())
                    dialog.dismiss();
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(),
                        e.getMessage(),
                        Toast.LENGTH_LONG).show();
                Log.e(e.getClass().getName(), e.getMessage(), e);
            }
        }

    }

    public String getPath(Uri uri) {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        if (cursor != null) {
            // HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL            // THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA            int column_index = cursor .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } else            return null;
    }

    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);

        imgView.setImageBitmap(bitmap);

    }

}

+++++++++++++++++++++++++
<?php

require_once"konmysqli.php";
$file_path = "ypathfile/";
$kode_anggota="AGT1810001";
$judul="Helo World M8";
$keterangan="Tes Versi Beta 1 #Helo World M8";
    
$IMG=$_FILES['uploaded_file']['name']; 
 
if(isset($_POST['kode_anggota'])){ 
 $kode_anggota=$_POST['kode_anggota']; 
 $judul=htmlentities($_POST['judul']); 
 $keterangan=htmlentities($_POST['keterangan']); 
}


$file_path = $file_path . basename( $IMG);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$file_path)){
 $file=$file_path;
 $source_properties = getimagesize($file);
 $image_type = $source_properties[2]; 
 

if( $image_type == IMAGETYPE_JPEG ) {   
 $image_resource_id = imagecreatefromjpeg($file);  
 $target_layer = fn_resize($image_resource_id,$source_properties[0],$source_properties[1]);
 imagejpeg($target_layer,$file_path);
}
elseif( $image_type == IMAGETYPE_GIF )  {  
 $image_resource_id = imagecreatefromgif($file);
 $target_layer = fn_resize($image_resource_id,$source_properties[0],$source_properties[1]);
 imagegif($target_layer,$file_path);
}
elseif( $image_type == IMAGETYPE_PNG ) {
 $image_resource_id = imagecreatefrompng($file); 
 $target_layer = fn_resize($image_resource_id,$source_properties[0],$source_properties[1]);
 imagepng($target_layer,$file_path );
}

  $tgl=date("Y-m-d");
  $jam=date("H:i:s");

 
   $sql=" INSERT INTO `tb_galeri` (
`id_galeri` ,
`kode_anggota` ,
`judul` ,
`keterangan` ,
`tgl` ,
`jam` ,
`gambar` 
) VALUES (
'', 
'$kode_anggota',
'$judul', 
'$keterangan',
'$tgl',
'$jam', 
'$IMG'
)";
 
 mysqli_query($conn,$sql);
    } //uploaded_file
 else{
        echo "fail";
    }
 
 

function fn_resize($image_resource_id,$width,$height) {
$size = getimagesize($image_resource_id);
$ratio = $size[0]/$size[1]; // width/height
if( $ratio > 1) {
    $target_width = 200;
    $target_height = 200/$ratio;
}
else {
    $target_width = 200*$ratio;
    $target_height = 200;
}

$target_layer=imagecreatetruecolor($target_width,$target_height);
imagecopyresampled($target_layer,$image_resource_id,0,0,0,0,$target_width,$target_height, $width,$height);
return $target_layer;
}



/*
list($width, $height, $type, $attr) = getimagesize($image_resource_id);

Width: 200
Height: 100
Type: 2
Attribute: width='200' height='100'



Type of image consider like -

1 = GIF
2 = JPG
3 = PNG
4 = SWF
5 = PSD
6 = BMP
7 = TIFF(intel byte order)
8 = TIFF(motorola byte order)
9 = JPC
10 = JP2
11 = JPX
12 = JB2
13 = SWC
14 = IFF
15 = WBMP
16 = XBM
*/
?>