2016-05-09 37 views
1

こんにちは、誰かが私がblobとしてデータベースに保管すべきではないと言う前に、私は私の理由が必要です。私はこれを聞いた最後の時間は、私はデータベースや何かにストアをしないようにしていた。さて、ここで私のコードは、他の部分は動作しない部分は動作する部分は、写真を撮って、それをimageviewで表示され、作業していないmysqlデータベースにアップロードされます。より多くの情報が必要な場合は、私は答えを編集することを教えてください。前もって感謝します。イメージをmysqlデータベースにアンドロイドでアップロードする

コード

活動:

public class takefoto extends BaseNavegationActivity { 

Button takebt, sendbt; 
String ba1; 
String mCurrentPhotoPath; 
ImageView mFoto; 
int CodServico; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.takefoto); 

    takebt = (Button) findViewById(R.id.takebt); 
    mFoto = (ImageView) findViewById(R.id.fotoser); 
    takebt.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      captureImage(); 
     } 
    }); 

    sendbt = (Button) findViewById(R.id.sendbt); 
    sendbt.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      upload(); 
     } 
    }); 

    Bundle extras = getIntent().getExtras(); 
    CodServico=extras.getInt("CodServico"); 
    Log.i("CODSERVICO",CodServico+""); 

} 

private void upload() { 
    Bitmap bm = BitmapFactory.decodeFile(mCurrentPhotoPath); 
    ByteArrayOutputStream bao = new ByteArrayOutputStream(); 
    bm.compress(Bitmap.CompressFormat.JPEG, 50, bao); 
    byte[] ba = bao.toByteArray(); 
    ba1 = Base64.encodeToString(ba,Base64.DEFAULT); 

    // Upload image to server 
    ServerRequests serverRequests = new ServerRequests(takefoto.this); 
    serverRequests.storeFotoDataInBackground(ba1, CodServico, new GetUpdaterCallBack() { 
     @Override 
     public void done(String returnUser) { 
      if (returnUser.equalsIgnoreCase("sucesso")) { 
       Toast.makeText(getApplicationContext(),"Enviado!",Toast.LENGTH_SHORT).show(); 
      } else{ 
       showError(); 
      } 
     } 
    }); 

} 

private void captureImage() { 
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
    // Ensure that there's a camera activity to handle the intent 
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) { 
     // Create the File where the photo should go 
     File photoFile = null; 
     try { 
      photoFile = createImageFile(); 
     } catch (IOException ex) { 
      // Error occurred while creating the File 
      ex.printStackTrace(); 
     } 
     // Continue only if the File was successfully created 
     if (photoFile != null) { 
      takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, 
        Uri.fromFile(photoFile)); 
      startActivityForResult(takePictureIntent, 100); 
     } 
    } 
} 

protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    if (requestCode == 100 && resultCode == RESULT_OK) { 
     setPic(); 
    } 
} 

private void setPic() { 
    // Get the dimensions of the View 
    int targetW = mFoto.getWidth(); 
    int targetH = mFoto.getHeight(); 

    // Get the dimensions of the bitmap 
    BitmapFactory.Options bmOptions = new BitmapFactory.Options(); 
    bmOptions.inJustDecodeBounds = true; 
    BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions); 
    int photoW = bmOptions.outWidth; 
    int photoH = bmOptions.outHeight; 

    // Determine how much to scale down the image 
    int scaleFactor = Math.min(photoW/targetW, photoH/targetH); 

    // Decode the image file into a Bitmap sized to fill the View 
    bmOptions.inJustDecodeBounds = false; 
    bmOptions.inSampleSize = scaleFactor; 
    bmOptions.inPurgeable = true; 

    Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions); 
    mFoto.setImageBitmap(bitmap); 
} 

private File createImageFile() throws IOException { 
    // Create an image file name 
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); 
    String imageFileName = "JPEG_" + timeStamp + "_"; 
    File storageDir = Environment.getExternalStoragePublicDirectory(
      Environment.DIRECTORY_PICTURES); 

    File image = File.createTempFile(
      imageFileName, /* prefix */ 
      ".jpg",   /* suffix */ 
      storageDir  /* directory */ 
    ); 

    // Save a file: path for use with ACTION_VIEW intents 
    mCurrentPhotoPath = image.getAbsolutePath(); 
    Log.e("Getpath", "Cool" + mCurrentPhotoPath); 
    return image; 
} 

private void showError(){ 
    android.app.AlertDialog.Builder dialogBuilder=new android.app.AlertDialog.Builder(getBaseContext()); 
    dialogBuilder.setMessage("Ocorreu um erro, por favor tente novamente mais tarde."); 
    dialogBuilder.setPositiveButton("Ok", null); 
    dialogBuilder.show(); 
} 
} 

ServerResquest方法:

public void storeFotoDataInBackground(String ba, int codservico,GetUpdaterCallBack userCallback){ 
    progressDialog.show(); 
    new StoreFotoDataAsyncTasck(ba, codservico, userCallback).execute(); 
} 
public class StoreFotoDataAsyncTasck extends AsyncTask<Void, Void, String> { 
    String ba; 
    int CodServico; 
    GetUpdaterCallBack registerCallback; 

    public StoreFotoDataAsyncTasck(String ba1, int codservico,GetUpdaterCallBack registerCallback) { 
     this.ba = ba1; 
     this.CodServico=codservico; 
     this.registerCallback = registerCallback; 
    } 

    @Override 
    protected String doInBackground(Void... params) { 
     String retorno = null; 
     try { 

      URL url = new URL(SERVER_ADDRESS + "myphpfile.php"); 
      HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
      Uri.Builder builder = new Uri.Builder() 
        .appendQueryParameter("CodServico", this.CodServico+"") 
        .appendQueryParameter("Imagem", this.ba); 
      Log.i("IMAGEM",this.ba+" CodServico"+this.CodServico); 
      final String postParameters = builder.build().getEncodedQuery(); 
      conn.setConnectTimeout(3000); 
      conn.setReadTimeout(3000); 
      conn.setRequestMethod("POST"); 
      conn.setFixedLengthStreamingMode(postParameters.getBytes().length); 
      conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
      conn.setDoInput(true); 
      conn.setDoOutput(true); 

      //send the POST out 
      PrintWriter pw = new PrintWriter(conn.getOutputStream()); 
      pw.print(postParameters); 
      pw.close(); 
      conn.connect(); 
      String result = convertStreamToString(conn.getInputStream()); 
      JSONObject jObject = new JSONObject(result); 
      if(jObject.length()!=0){ 
       retorno= jObject.getString("estado"); 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     return retorno; 
    } 
} 

私のPHPコード:

<?php 
$codservic=$_POST['CodServico'];   
$image = $_POST['Imagem'];   
$con = mysqli_connect("xxxxxxxxx","xxxxxxxx","xxxxxxxxx","xxxxxxxxxx") or die('Unable To connect'); 
$sql = "insert into xxxxxxxx (xxxxxxxx,xxxxxxxx) values(?,?)"; 
$stmt = mysqli_prepare($con,$sql); 
mysqli_stmt_bind_param($stmt,"is",$codservic,$image); 
$sucesso=mysqli_stmt_execute($stmt); 
if($sucesso){ 
    $estado = array(); 
    $estado[estado] = "sucesso"; 
    echo json_encode($estado); 
} 
?> 

答えて

0

まあ、多くの検索の後、私は仕事にfinnalyそれを得ましたあなたは誰ですか?それも私は私のコードを投稿しますエド。

主な活動:

public class takefoto extends BaseNavegationActivity { 

Button takebt, sendbt; 
String ba1; 
String mCurrentPhotoPath; 
ImageView mFoto; 
int CodServico; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.takefoto); 

    takebt = (Button) findViewById(R.id.takebt); 
    mFoto = (ImageView) findViewById(R.id.fotoser); 
    takebt.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      captureImage(); 
     } 
    }); 

    sendbt = (Button) findViewById(R.id.sendbt); 
    sendbt.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      upload(); 
     } 
    }); 

    Bundle extras = getIntent().getExtras(); 
    CodServico=extras.getInt("CodServico"); 
    Log.i("CODSERVICO",CodServico+""); 

} 

private void upload() { 
    Bitmap bm = BitmapFactory.decodeFile(mCurrentPhotoPath); 
    ByteArrayOutputStream bao = new ByteArrayOutputStream(); 
    bm.compress(Bitmap.CompressFormat.JPEG, 50, bao); 
    byte[] ba = bao.toByteArray(); 
    Log.i("IMAGEM NAO CONVERTIDA",ba+""); 
    ba1 = Base64.encodeToString(ba,Base64.DEFAULT); 
    // Get image and 
    // Upload image to server 
    ServerRequests serverRequests = new ServerRequests(takefoto.this); 
    serverRequests.storeFotoDataInBackground(ba1, CodServico, new GetUpdaterCallBack() { 
     @Override 
     public void done(String returnUser) { 
      if (returnUser.equalsIgnoreCase("sucesso")) { 
       Toast.makeText(getApplicationContext(),"Enviado!",Toast.LENGTH_SHORT).show(); 
      } else{ 
       showError(); 
      } 
     } 
    }); 

} 

private void captureImage() { 
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
    // Ensure that there's a camera activity to handle the intent 
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) { 
     // Create the File where the photo should go 
     File photoFile = null; 
     try { 
      photoFile = createImageFile(); 
     } catch (IOException ex) { 
      // Error occurred while creating the File 
      ex.printStackTrace(); 
     } 
     // Continue only if the File was successfully created 
     if (photoFile != null) { 
      takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, 
        Uri.fromFile(photoFile)); 
      startActivityForResult(takePictureIntent, 100); 
     } 
    } 
} 

protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    if (requestCode == 100 && resultCode == RESULT_OK) { 
     setPic(); 
    } 
} 

private void setPic() { 
    // Get the dimensions of the View 
    int targetW = mFoto.getWidth(); 
    int targetH = mFoto.getHeight(); 

    // Get the dimensions of the bitmap 
    BitmapFactory.Options bmOptions = new BitmapFactory.Options(); 
    bmOptions.inJustDecodeBounds = true; 
    BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions); 
    int photoW = bmOptions.outWidth; 
    int photoH = bmOptions.outHeight; 

    // Determine how much to scale down the image 
    int scaleFactor = Math.min(photoW/targetW, photoH/targetH); 

    // Decode the image file into a Bitmap sized to fill the View 
    bmOptions.inJustDecodeBounds = false; 
    bmOptions.inSampleSize = scaleFactor; 
    bmOptions.inPurgeable = true; 

    Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions); 
    mFoto.setImageBitmap(bitmap); 
} 

private File createImageFile() throws IOException { 
    // Create an image file name 
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); 
    String imageFileName = "JPEG_" + timeStamp + "_"; 
    File storageDir = Environment.getExternalStoragePublicDirectory(
      Environment.DIRECTORY_PICTURES); 

    File image = File.createTempFile(
      imageFileName, /* prefix */ 
      ".jpg",   /* suffix */ 
      storageDir  /* directory */ 
    ); 

    // Save a file: path for use with ACTION_VIEW intents 
    mCurrentPhotoPath = image.getAbsolutePath(); 
    Log.e("Getpath", "Cool" + mCurrentPhotoPath); 
    return image; 
} 

private void showError(){ 
    android.app.AlertDialog.Builder dialogBuilder=new android.app.AlertDialog.Builder(getBaseContext()); 
    dialogBuilder.setMessage("Ocorreu um erro, por favor tente novamente mais tarde."); 
    dialogBuilder.setPositiveButton("Ok", null); 
    dialogBuilder.show(); 
} 
} 

Serverリクエスト方法(データベースとインサートの一部):

@Override 
    protected String doInBackground(Void... params) { 
     String retorno = null; 
     try { 

      URL url = new URL(SERVER_ADDRESS + "yourphpfile.php"); 
      HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
      Uri.Builder builder = new Uri.Builder() 
        .appendQueryParameter("Value1", this.CodServico+"") 
        .appendQueryParameter("Image", this.ba); 
      Log.i("IMAGEM",""+this.ba); 
      final String postParameters = builder.build().getEncodedQuery(); 
      conn.setConnectTimeout(3000); 
      conn.setReadTimeout(3000); 
      conn.setRequestMethod("POST"); 
      conn.setFixedLengthStreamingMode(postParameters.getBytes().length); 
      conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
      conn.setDoInput(true); 
      conn.setDoOutput(true); 

      //send the POST out 
      PrintWriter pw = new PrintWriter(conn.getOutputStream()); 
      pw.print(postParameters); 
      pw.close(); 
      conn.connect(); 
      String result = convertStreamToString(conn.getInputStream()); 
      JSONObject jObject = new JSONObject(result); 
      if(jObject.length()!=0){ 
       retorno= jObject.getString("status");// if was sucess or not 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     return retorno; 
    } 

私のPHPコード:

<?php 
$codservic=$_POST['Value1'];  
$image = $_POST['Image']; 
header("Content-type: image/jpg"); 
$img = base64_decode($image); 
$con = mysqli_connect("your connection string") or die('Unable To connect'); 
$sql = "insert into yourtable (yourcamp1,image) values(?,?)"; 
$stmt = mysqli_prepare($con,$sql); 
mysqli_stmt_bind_param($stmt,"is",$codservic,$img); 
$sucesso=mysqli_stmt_execute($stmt); 
$estado = array(); 
if($sucesso){ 
    $estado[status] = "sucess"; 
    echo json_encode($estado); 
} else { 
    $estado[status] = "error"; 
    echo json_encode($estado); 
} 
?> 
関連する問題