public Object getObject(String str) { try { Object string = getString(str); if (TextUtils.isEmpty(string)) { return null; } ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream (Base64.decode(string, 2))); string = objectInputStream.readObject(); objectInputStream.close(); return string; } catch (Throwable th) { Ln.w(th); return null; } }
/** * 按照默认设置的压缩质量 * 将 Bitmap 转换为 Base64 照片字符串 * * @param bmp * @return */ public static final Observable<String> bmpToBase64(Bitmap bmp) { int quality = 100; if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) { // 4.0 及以下 quality = 50; } if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN_MR2) { // 4.3 及以下 quality = 60; } if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { // 5.0 以下 quality = 70; } return bmpToBase64(bmp, Bitmap.CompressFormat.JPEG, quality, Base64.NO_WRAP); }
/** * An aes key derived from a base64 encoded key. This does not generate the * key. It's not random or a PBE key. * * @param keysStr a base64 encoded AES key / hmac key as base64(aesKey) : base64(hmacKey). * @return an AES & HMAC key set suitable for other functions. */ public static SecretKeys keys(String keysStr) throws InvalidKeyException { String[] keysArr = keysStr.split(":"); if (keysArr.length != 2) { throw new IllegalArgumentException("Cannot parse aesKey:hmacKey"); } else { byte[] confidentialityKey = Base64.decode(keysArr[0], BASE64_FLAGS); if (confidentialityKey.length != AES_KEY_LENGTH_BITS /8) { throw new InvalidKeyException("Base64 decoded key is not " + AES_KEY_LENGTH_BITS + " bytes"); } byte[] integrityKey = Base64.decode(keysArr[1], BASE64_FLAGS); if (integrityKey.length != HMAC_KEY_LENGTH_BITS /8) { throw new InvalidKeyException("Base64 decoded key is not " + HMAC_KEY_LENGTH_BITS + " bytes"); } return new SecretKeys( new SecretKeySpec(confidentialityKey, 0, confidentialityKey.length, CIPHER), new SecretKeySpec(integrityKey, HMAC_ALGORITHM)); } }
/** * 加密数据 * * @param str str * @return 加密失败可能为null */ public static String encryptStr(String str) { try { PublicKey publicKey = getPublicKey(RSA_MODULUS, RSA_PUBLIC_EXPONENT); // 加解密类 Cipher cipher = Cipher.getInstance("RSA"); // "RSA/ECB/PKCS1Padding" // 加密 cipher.init(Cipher.ENCRYPT_MODE, publicKey); byte[] dataEncode = cipher.doFinal(str.getBytes()); // 为了可读性,转为Base64, byte[] tmp = Base64.encode(dataEncode, BASE64_FLAGS); return new String(tmp); } catch (Exception e) { e.printStackTrace(); } return null; }
private String i(String str) { ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(str.getBytes()); OutputStream byteArrayOutputStream = new ByteArrayOutputStream(); String str2 = null; try { GZIPOutputStream gZIPOutputStream = new GZIPOutputStream(byteArrayOutputStream); byte[] bArr = new byte[1024]; while (true) { int read = byteArrayInputStream.read(bArr, 0, 1024); if (read == -1) { break; } gZIPOutputStream.write(bArr, 0, read); } gZIPOutputStream.flush(); gZIPOutputStream.close(); byte[] toByteArray = byteArrayOutputStream.toByteArray(); byteArrayOutputStream.flush(); byteArrayOutputStream.close(); byteArrayInputStream.close(); str2 = Base64.encodeToString(toByteArray, 2); } catch (Throwable e) { Ln.e(e); } return str2; }
/** * 将对象储存到sharepreference * * @param key * @param device * @param <T> */ public static <T> boolean saveDeviceData(Context context, String key, T device) { if (mSharedPreferences == null) { mSharedPreferences = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { //Device为自定义类 // 创建对象输出流,并封装字节流 ObjectOutputStream oos = new ObjectOutputStream(baos); // 将对象写入字节流 oos.writeObject(device); // 将字节流编码成base64的字符串 String oAuth_Base64 = new String(Base64.encode(baos .toByteArray(), Base64.DEFAULT)); mSharedPreferences.edit().putString(key, oAuth_Base64).commit(); return true; } catch (Exception e) { e.printStackTrace(); return false; } }
public static String textCompress(String str) { try { Object array = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(str.length()).array(); OutputStream byteArrayOutputStream = new ByteArrayOutputStream(str.length()); GZIPOutputStream gZIPOutputStream = new GZIPOutputStream(byteArrayOutputStream); gZIPOutputStream.write(str.getBytes("UTF-8")); gZIPOutputStream.close(); byteArrayOutputStream.close(); Object obj = new byte[(byteArrayOutputStream.toByteArray().length + 4)]; System.arraycopy(array, 0, obj, 0, 4); System.arraycopy(byteArrayOutputStream.toByteArray(), 0, obj, 4, byteArrayOutputStream.toByteArray().length); return Base64.encodeToString(obj, 8); } catch (Exception e) { return ""; } }
public HttpPeerConnector(String peerUrl, SiteToSiteClientConfig siteToSiteClientConfig, SiteToSiteRemoteCluster siteToSiteRemoteCluster) { this.peerUrl = peerUrl; this.siteToSiteClientConfig = siteToSiteClientConfig; this.siteToSiteRemoteCluster = siteToSiteRemoteCluster; SSLContext sslContext = siteToSiteRemoteCluster.getSslContext(); if (sslContext != null) { socketFactory = sslContext.getSocketFactory(); } else { socketFactory = null; } proxy = getProxy(siteToSiteRemoteCluster); String proxyUsername = siteToSiteRemoteCluster.getProxyUsername(); if (proxy != null && proxyUsername != null && !proxyUsername.isEmpty()) { proxyAuth = siteToSiteRemoteCluster.getProxyAuthorizationType() + " " + Base64.encodeToString((proxyUsername + ":" + siteToSiteRemoteCluster.getProxyPassword()).getBytes(Charsets.ISO_8859_1), Base64.DEFAULT); } else { proxyAuth = null; } }
private void processIniciatorState1(int accountId, int peerId, @NonNull KeyExchangeSession session, @NonNull ExchangeMessage message) { String hisAesKey = message.getAesKey(); PrivateKey myPrivateKey = session.getMyPrivateKey(); try { byte[] hisAesEncoded = Base64.decode(hisAesKey, Base64.DEFAULT); String hisOriginalAes = CryptHelper.decryptRsa(hisAesEncoded, myPrivateKey); session.setHisAesKey(hisOriginalAes); String myOriginalAesKey = CryptHelper.generateRandomAesKey(Version.ofCurrent().getAesKeySize()); session.setMyAesKey(myOriginalAesKey); PublicKey hisPublicKey = CryptHelper.createRsaPublicKeyFromString(message.getPublicKey()); byte[] myEncodedAesKey = CryptHelper.encryptRsa(myOriginalAesKey, hisPublicKey); String myEncodedAesKeyBase64 = Base64.encodeToString(myEncodedAesKey, Base64.DEFAULT); Logger.d(TAG, "processIniciatorState1, myOriginalAesKey: " + myOriginalAesKey + ", hisOriginalAes: " + hisOriginalAes); ExchangeMessage m = new ExchangeMessage.Builder(Version.CURRENT, session.getId(), SessionState.INITIATOR_STATE_2) .setAesKey(myEncodedAesKeyBase64) .create(); sendMessage(accountId, peerId, m); } catch (InvalidKeyException | BadPaddingException | IllegalBlockSizeException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeySpecException e) { e.printStackTrace(); } }
/** * Decode the user's email address from Base64 * * @param accountList the {@link SaiyAccountList} object * @return the updated {@link SaiyAccountList} */ private static SaiyAccountList decode(@NonNull final SaiyAccountList accountList) { try { for (final SaiyAccount account : accountList.getSaiyAccountList()) { account.setAccountName(new String(Base64.decode(account.getAccountName(), Base64.NO_WRAP), Constants.ENCODING_UTF8)); } } catch (final UnsupportedEncodingException e) { if (DEBUG) { MyLog.w(CLS_NAME, "encode UnsupportedEncodingException"); e.printStackTrace(); } } return accountList; }
public String getStringImage(Bitmap bmp){ ByteArrayOutputStream baos = new ByteArrayOutputStream(); bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos); byte[] imageBytes = baos.toByteArray(); String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT); return encodedImage; }
void getImage() //profile pic { ImageRequest request = new ImageRequest("http://ec2-52-14-50-89.us-east-2.compute.amazonaws.com/static/userdata/"+name+"/thumb.png", ///"+email+" in btw userdata/ /thumb.png new Response.Listener<Bitmap>() { @Override public void onResponse(Bitmap bitmap) { pro=bitmap; ByteArrayOutputStream baos=new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG,100, baos); byte [] b=baos.toByteArray(); String temp= Base64.encodeToString(b, Base64.DEFAULT); SharedPreferences.Editor editor=sharedPreferences.edit(); editor.putString("profile_pic",temp); editor.commit(); Log.e("mytag","Saved propic"+pro); //count++; } }, 0, 0, null, new Response.ErrorListener() { public void onErrorResponse(VolleyError error) { // mImageView.setImageResource(R.drawable.image_load_error); Log.e("Home_Acitivity","No img found"); //count++; } }); // MySingleton.getMyInstance(getApplicationContext()).addToReqQue(request); RequestQueue queue= Volley.newRequestQueue(getApplicationContext()); queue.add(request); }
public static String decrypt( String password, String encryptedData ) throws Exception { byte[] secretKey = generateKey( password.getBytes() ); SecretKeySpec secretKeySpec = new SecretKeySpec( secretKey, CIPHER_ALGORITHM ); Cipher cipher = Cipher.getInstance( CIPHER_ALGORITHM ); cipher.init( Cipher.DECRYPT_MODE, secretKeySpec ); byte[] encrypted = Base64.decode( encryptedData, Base64.DEFAULT ); byte[] decrypted = cipher.doFinal( encrypted ); return new String( decrypted ); }
public void setHTML(byte bytes[]) { // preserve zoom level between pages int zoom = (int)(100 * mScale); String b64 = Base64.encodeToString(bytes, Base64.DEFAULT); loadData(b64, "text/html; charset=utf-8", "base64"); setInitialScale(zoom); scrollTo(0, 0); }
public static Bitmap decodeImage(String imageString) { try { byte[] encodeByte = Base64.decode(imageString, Base64.DEFAULT); Bitmap bitmap = BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length); return bitmap; } catch (Exception e) { e.getMessage(); return null; } }
private void injectLightBlueCSS(String mode) { try { InputStream inputStream = getAssets().open("light_blue_theme.css"); byte[] buffer = new byte[inputStream.available()]; inputStream.read(buffer); inputStream.close(); webView.loadUrl("javascript:(function() {var parent = document.getElementsByTagName('head').item(0);var style = document.createElement('style');style.type = 'text/css';style.innerHTML = window.atob('" + Base64.encodeToString(buffer, 2) + "');" + "parent.appendChild(style)" + "})()"); } catch (Exception d) { d.printStackTrace(); } }
private void injectPinkCSS(String mode) { try { InputStream inputStream = getAssets().open("pink_theme.css"); byte[] buffer = new byte[inputStream.available()]; inputStream.read(buffer); inputStream.close(); webView.loadUrl("javascript:(function() {var parent = document.getElementsByTagName('head').item(0);var style = document.createElement('style');style.type = 'text/css';style.innerHTML = window.atob('" + Base64.encodeToString(buffer, 2) + "');" + "parent.appendChild(style)" + "})()"); } catch (Exception d) { d.printStackTrace(); } }
public SpannableStringBuilder processCrontab() { SpannableStringBuilder ret = new SpannableStringBuilder(); String hashedTab = ""; try { MessageDigest messageDigest = MessageDigest.getInstance(HASH_ALGO); messageDigest.update(crontab.getBytes()); hashedTab = Base64.encodeToString(messageDigest.digest(), Base64.DEFAULT).trim(); } catch (NoSuchAlgorithmException e) { Log.e(TAG, String.format("Algorithm %s not found:", HASH_ALGO)); e.printStackTrace(); } if (!hashedTab.equals(sharedPrefs.getString(PREF_CRONTAB_HASH, "")) && !crontab.equals("")) { // only schedule when enabled if (sharedPrefs.getBoolean(PREF_ENABLED, false)) { IO.logToLogFile(context.getString(R.string.log_crontab_change_detected)); scheduleCrontab(); } // save in any case such that on installation the crontab is not "new" sharedPrefs.edit().putString(PREF_CRONTAB_HASH, hashedTab).apply(); } if (crontab.equals("")) { return ret; } for (String line : crontab.split("\n")){ ret.append(line + "\n", new TypefaceSpan("monospace"), Spanned.SPAN_COMPOSING); ret.append(describeLine(line)); } return ret; }
public static String decrypt(String input) { if(input == null) return null; byte[] decrypted = null; try{ SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, skey); decrypted = cipher.doFinal(Base64.decode(input, Base64.DEFAULT)); } catch(Exception e){ e.printStackTrace(); } return new String(decrypted); }
private void injectDarkCSS(String mode) { try { InputStream inputStream = getAssets().open("black.css"); byte[] buffer = new byte[inputStream.available()]; inputStream.read(buffer); inputStream.close(); webView.loadUrl("javascript:(function() {var parent = document.getElementsByTagName('head').item(0);var style = document.createElement('style');style.type = 'text/css';style.innerHTML = window.atob('" + Base64.encodeToString(buffer, 2) + "');" + "parent.appendChild(style)" + "})()"); } catch (Exception b) { b.printStackTrace(); } }
private static PendingInstallShortcutInfo decode(String encoded, Context context) { try { JSONObject object = (JSONObject) new JSONTokener(encoded).nextValue(); Intent launcherIntent = Intent.parseUri(object.getString(LAUNCH_INTENT_KEY), 0); if (object.optBoolean(APP_SHORTCUT_TYPE_KEY)) { // The is an internal launcher target shortcut. UserHandleCompat user = UserManagerCompat.getInstance(context) .getUserForSerialNumber(object.getLong(USER_HANDLE_KEY)); if (user == null) { return null; } LauncherActivityInfoCompat info = LauncherAppsCompat.getInstance(context) .resolveActivity(launcherIntent, user); return info == null ? null : new PendingInstallShortcutInfo(info, context); } Intent data = new Intent(); data.putExtra(Intent.EXTRA_SHORTCUT_INTENT, launcherIntent); data.putExtra(Intent.EXTRA_SHORTCUT_NAME, object.getString(NAME_KEY)); String iconBase64 = object.optString(ICON_KEY); String iconResourceName = object.optString(ICON_RESOURCE_NAME_KEY); String iconResourcePackageName = object.optString(ICON_RESOURCE_PACKAGE_NAME_KEY); if (iconBase64 != null && !iconBase64.isEmpty()) { byte[] iconArray = Base64.decode(iconBase64, Base64.DEFAULT); Bitmap b = BitmapFactory.decodeByteArray(iconArray, 0, iconArray.length); data.putExtra(Intent.EXTRA_SHORTCUT_ICON, b); } else if (iconResourceName != null && !iconResourceName.isEmpty()) { Intent.ShortcutIconResource iconResource = new Intent.ShortcutIconResource(); iconResource.resourceName = iconResourceName; iconResource.packageName = iconResourcePackageName; data.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource); } return new PendingInstallShortcutInfo(data, context); } catch (JSONException | URISyntaxException e) { Log.d(TAG, "Exception reading shortcut to add: " + e); } return null; }
private String createBody() { String sSPS; String sPPS; if (sps != null && pps != null) { sSPS = Base64.encodeToString(sps, 0, sps.length, Base64.NO_WRAP); sPPS = Base64.encodeToString(pps, 0, pps.length, Base64.NO_WRAP); } else { sSPS = defaultSPS; sPPS = defaultPPS; } return "v=0\r\n" + // TODO: Add IPV6 support "o=- " + timestamp + " " + timestamp + " IN IP4 " + "127.0.0.1" + "\r\n" + "s=Unnamed\r\n" + "i=N/A\r\n" + "c=IN IP4 " + host + "\r\n" + // means the session is permanent "t=0 0\r\n" + "a=recvonly\r\n" + Body.createAudioBody(trackAudio, sampleRate, isStereo) + Body.createVideoBody(trackVideo, sSPS, sPPS); }
/** Checks whether given plaintext password corresponds to a stored salted hash of the password. */ public static boolean check(String password, String stored) throws Exception{ String[] saltAndPass = stored.split("\\$"); if (saltAndPass.length != 2) { throw new IllegalStateException( "The stored password have the form 'salt$hash'"); } String hashOfInput = hash(password, Base64.decode(saltAndPass[0], Base64.DEFAULT)); return hashOfInput.equals(saltAndPass[1]); }
/** * Encodes this ciphertext, IV, mac as a string. * * @return base64(iv) : base64(mac) : base64(ciphertext). * The iv and mac go first because they're fixed length. */ @Override public String toString() { String ivString = Base64.encodeToString(iv, BASE64_FLAGS); String cipherTextString = Base64.encodeToString(cipherText, BASE64_FLAGS); String macString = Base64.encodeToString(mac, BASE64_FLAGS); return String.format(ivString + ":" + macString + ":" + cipherTextString); }
/** * AES加密 * @param input 加密字符串 * @param key 密钥,密钥必须是16位的 * @return */ public static String encrypt(@NonNull String input, @NonNull String key){ byte[] crypted = null; try{ SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, skey); crypted = cipher.doFinal(input.getBytes()); }catch(Exception e){ System.out.println(e.toString()); } return new String(Base64.encode(crypted, Base64.DEFAULT)); }
/** * Decodes the encodedPhoto and sets the photo Bitmap to it. */ private void decodePhoto() { if (this.encodedPhoto != null) { byte [] decodedBytes = Base64.decode(this.encodedPhoto, 0); this.photo = BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.length); } }
private void injectGPlusCSS(String mode) { try { InputStream inputStream = getAssets().open("gplus_theme.css"); byte[] buffer = new byte[inputStream.available()]; inputStream.read(buffer); inputStream.close(); webView.loadUrl("javascript:(function() {var parent = document.getElementsByTagName('head').item(0);var style = document.createElement('style');style.type = 'text/css';style.innerHTML = window.atob('" + Base64.encodeToString(buffer, 2) + "');" + "parent.appendChild(style)" + "})()"); } catch (Exception d) { d.printStackTrace(); } }
private void injectDefaultCSS(String mode) { try { InputStream inputStream = getAssets().open("fbdefault.css"); byte[] buffer = new byte[inputStream.available()]; inputStream.read(buffer); inputStream.close(); webView.loadUrl("javascript:(function() {var parent = document.getElementsByTagName('head').item(0);var style = document.createElement('style');style.type = 'text/css';style.innerHTML = window.atob('" + Base64.encodeToString(buffer, 2) + "');" + "parent.appendChild(style)" + "})()"); } catch (Exception fb) { fb.printStackTrace(); } }
private void getActions(final DeviceDAO device) { Log.d(TAG, "TODO getActions"); String uri = Uri.parse(String.format("http://%s:%s/", device.getIP(), device.getPort())) .buildUpon().build().toString(); String credentials = device.getUsername() + ":" + device.getPassword(); byte[] t = credentials.getBytes(); byte[] auth = Base64.encode(t, Base64.DEFAULT); final String basicAuthValue = new String(auth); requestQueue.add(new StringRequest(Request.Method.POST, uri, new Response.Listener<String>() { @Override public void onResponse(String response) { } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }) { @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> params = new HashMap<>(); params.put("Authorization", "Basic " + basicAuthValue); params.put("Connection", "close"); return params; } }); }
public static Server decode(String data) { final String[] split = data.split(";"); final String name = new String(Base64.decode(split[0], Base64.DEFAULT)); final String uuid = split[1]; return new Server(name, uuid); }
/** * 用公钥解密 * * @param data 加密数据 * @param key 密钥 * @return * @throws Exception */ public static String decryptByPublicKey(String data, String key) throws Exception { //对私钥解密 byte[] keyBytes = Base64.decode(key.getBytes(), Base64.DEFAULT); X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); Key publicKey = keyFactory.generatePublic(x509EncodedKeySpec); //对数据解密 Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.DECRYPT_MODE, publicKey); byte[] dataBytes = Base64.decode(data.getBytes(), Base64.DEFAULT); byte[] resultBytes = cipher.doFinal(dataBytes); return new String(resultBytes, "UTF-8"); }
private static String bitmapToBase64(Bitmap bitmap) { ByteArrayOutputStream stream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); byte[] byteArray = stream.toByteArray(); IOUtils.closeQuietly(stream); return "data:image/png;base64," + Base64.encodeToString(byteArray, Base64.DEFAULT); }
/** * Checks whether underlying platform supports extended WebPs */ private static boolean isExtendedWebpSupported() { // Lossless and extended formats are supported on Android 4.2.1+ // Unfortunately SDK_INT is not enough to distinguish 4.2 and 4.2.1 // (both are API level 17 (JELLY_BEAN_MR1)) if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) { return false; } if (Build.VERSION.SDK_INT == Build.VERSION_CODES.JELLY_BEAN_MR1) { // Let's test if extended webp is supported // To this end we will try to decode bounds of vp8x webp with alpha channel byte[] decodedBytes = Base64.decode(VP8X_WEBP_BASE64, Base64.DEFAULT); BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inJustDecodeBounds = true; BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.length, opts); // If Android managed to find appropriate decoder then opts.outHeight and opts.outWidth // should be set. We can not assume that outMimeType is set. // Android guys forgot to update logic for mime types when they introduced support for webp. // For example, on 4.2.2 this field is not set for webp images. if (opts.outHeight != 1 || opts.outWidth != 1) { return false; } } return true; }
public boolean generateBase64FromImage() { try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); yuvImage.compressToJpeg(person.getFaceBounds(), 50, outputStream); this.jpeg = outputStream.toByteArray(); this.b64 = Base64.encodeToString(jpeg, Base64.DEFAULT); } catch (Exception e) { Log.d(TAG, "Exception while compressing YUVImage into JPEG - " + e.getMessage()); } finally { return (b64 != null); } }
public static String decodeString(String text) { try { return new String(Base64.decode(text, Base64.DEFAULT), "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return null; } }
public static String encodeImage(Bitmap bitmap) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos); byte[] b = baos.toByteArray(); String temp = Base64.encodeToString(b, Base64.DEFAULT); return temp; }
private OpenForReadResult readDataUri(Uri uri) { String uriAsString = uri.getSchemeSpecificPart(); int commaPos = uriAsString.indexOf(','); if (commaPos == -1) { return null; } String[] mimeParts = uriAsString.substring(0, commaPos).split(";"); String contentType = null; boolean base64 = false; if (mimeParts.length > 0) { contentType = mimeParts[0]; } for (int i = 1; i < mimeParts.length; ++i) { if ("base64".equalsIgnoreCase(mimeParts[i])) { base64 = true; } } String dataPartAsString = uriAsString.substring(commaPos + 1); byte[] data; if (base64) { data = Base64.decode(dataPartAsString, Base64.DEFAULT); } else { try { data = dataPartAsString.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { data = dataPartAsString.getBytes(); } } InputStream inputStream = new ByteArrayInputStream(data); return new OpenForReadResult(uri, inputStream, contentType, data.length, null); }
private void showFbBar(String mode) { try { InputStream inputStream = getAssets().open("showfbar.css"); byte[] buffer = new byte[inputStream.available()]; inputStream.read(buffer); inputStream.close(); webView.loadUrl("javascript:(function() {var parent = document.getElementsByTagName('head').item(0);var style = document.createElement('style');style.type = 'text/css';style.innerHTML = window.atob('" + Base64.encodeToString(buffer, 2) + "');" + "parent.appendChild(style)" + "})()"); } catch (Exception d) { d.printStackTrace(); } }
/** * string转成bitmap * * @param str 需要转换的字符串 * @return 失败时为null */ public static Bitmap str2Bitmap(String str) { Bitmap bitmap = null; try { byte[] bitmapArray = Base64.decode(str, Base64.DEFAULT); bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length); } catch (Exception e) { e.printStackTrace(); } return bitmap; }