`
程言方
  • 浏览: 46918 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论
收藏列表
标题 标签 来源
利用webView加载超长图 android
public static int showLargeImageView(WebView large, String url,
String bitmapPath) {
large.setVisibility(View.VISIBLE);
if (large.getTag() != null) {
return 0;
}
large.getSettings().setJavaScriptEnabled(true);
large.getSettings().setUseWideViewPort(true);
large.getSettings().setLoadWithOverviewMode(true);
large.getSettings().setBuiltInZoomControls(true);
large.getSettings().setDisplayZoomControls(false);

large.setVerticalScrollBarEnabled(false);
large.setHorizontalScrollBarEnabled(false);

File file = new File(bitmapPath);

if (file == null) {
return -1;
}

String str1 = "file://"
+ file.getAbsolutePath().replace("/mnt/sdcard/", "/sdcard/");
String str2 = "<html>\n<head>\n     <style>\n          html,body{background:transparent;margin:0;padding:0;}          *{-webkit-tap-highlight-color:rgba(0, 0, 0, 0);}\n     </style>\n     <script type=\"text/javascript\">\n     var imgUrl = \""
+ str1
+ "\";"
+ "     var objImage = new Image();\n"
+ "     var realWidth = 0;\n"
+ "     var realHeight = 0;\n"
+ "\n"
+ "     function onLoad() {\n"
+ "          objImage.onload = function() {\n"
+ "               realWidth = objImage.width;\n"
+ "               realHeight = objImage.height;\n"
+ "\n"
+ "               document.gagImg.src = imgUrl;\n"
+ "               onResize();\n"
+ "          }\n"
+ "          objImage.src = imgUrl;\n"
+ "     }\n"
+ "\n"
+ "     function onResize() {\n"
+ "          var scale = 1;\n"
+ "          var newWidth = document.gagImg.width;\n"
+ "          if (realWidth > newWidth) {\n"
+ "               scale = realWidth / newWidth;\n"
+ "          } else {\n"
+ "               scale = newWidth / realWidth;\n"
+ "          }\n"
+ "\n"
+ "          hiddenHeight = Math.ceil(30 * scale);\n"
+ "          document.getElementById('hiddenBar').style.height = hiddenHeight + \"px\";\n"
+ "          document.getElementById('hiddenBar').style.marginTop = -hiddenHeight + \"px\";\n"
+ "     }\n"
+ "     </script>\n"
+ "</head>\n"
+ "<body onload=\"onLoad()\" onresize=\"onResize()\" onclick=\"Android.toggleOverlayDisplay();\">\n"
+ "     <table style=\"width: 100%;height:100%;\">\n"
+ "          <tr style=\"width: 100%;\">\n"
+ "               <td valign=\"middle\" align=\"center\" style=\"width: 100%;\">\n"
+ "                    <div style=\"display:block\">\n"
+ "                         <img name=\"gagImg\" src=\"\" width=\"100%\" style=\"\" />\n"
+ "                    </div>\n"
+ "                    <div id=\"hiddenBar\" style=\"position:absolute; width: 100%; background: transparent;\"></div>\n"
+ "               </td>\n"
+ "          </tr>\n"
+ "     </table>\n" + "</body>\n" + "</html>";
large.loadDataWithBaseURL("file:///android_asset/", str2, "text/html",
"utf-8", null);
large.setVisibility(View.VISIBLE);
large.setTag(new Object());
return 1;
}
保存图片至相册 android
/**
* 将bitmap保存至相册
* photoName:照片名称
* bitmap:要保存的图像
* */
public static void savePhotoToAlbum(Context context, String photoName,
Bitmap bitmap) {
// 创建contentValuse对象,保存相片属性
ContentValues values = new ContentValues(7);
// 相片标题
values.put(Images.Media.TITLE,
context.getResources().getString(R.string.app_name));
// 相片名称
values.put(Images.Media.DISPLAY_NAME, photoName);
// 相片类型
values.put(Images.Media.MIME_TYPE, "image/jpeg");
// 相片方向
values.put(Images.Media.ORIENTATION, 0);
// 相片拍摄时间
String saveTime = DateFormat.format(DateTimeUtil.PATTERN_CURRENT_TIME,
System.currentTimeMillis()).toString();
values.put(Images.Media.DATE_TAKEN, saveTime);
// 相片路径
final String CAMERA_IMAGE_BUCKET_NAME = Environment
.getExternalStorageDirectory().getPath() + "dcim/camera";
File parentFile = new File(CAMERA_IMAGE_BUCKET_NAME);
String name = parentFile.getName().toLowerCase();
values.put(Images.ImageColumns.BUCKET_DISPLAY_NAME, name);
// 相片ID
final String CAMERA_IMAGE_BUCKET_ID = String
.valueOf(CAMERA_IMAGE_BUCKET_NAME.hashCode());
values.put(Images.ImageColumns.BUCKET_ID, CAMERA_IMAGE_BUCKET_ID);

// 将contentValuse转化为Uri
Uri dataUri = context.getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
// 根据Uri将图片写入相册
try {
OutputStream outStream = context.getContentResolver()
.openOutputStream(dataUri);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.close();
bitmap.recycle();
SuperToast.show("保存图片成功,请到相册查看!", context);
return;
} catch (Exception e) {
SuperToast.show("保存图片失败,请查看网络!", context);
}
}
图片等比例缩小 android
public static Bitmap getResizedBitmap(Bitmap bitmap, int height, int width) {
	int h = bitmap.getHeight();
	int w = bitmap.getWidth();
	if (w >= h && w >= width) {
		float ratio = (float) (height) / h;
		h = height;
		w = (int) (ratio * w);
	} else if (h > w && h > height) {
		float ratio = (float) (width) / w;
		w = width;
		h = (int) (ratio * h);
	}
	Bitmap resizedBitmap = Bitmap.createScaledBitmap(bitmap, w, h, true);
	return resizedBitmap;
}
根据bitmap或者file创建图片并等比例压缩 android
public static Bitmap createImg(byte[] aImgBytes) {
BitmapFactory.Options bitopt = new BitmapFactory.Options();
bitopt.inJustDecodeBounds = false;
Bitmap bit = null;
try {
bit = BitmapFactory.decodeByteArray(aImgBytes, 0, aImgBytes.length,bitopt);
} catch (OutOfMemoryError e) {
bit = null;
}
int _resizeTimes = 0;
int w = bitopt.outWidth / 2;
int h = bitopt.outHeight / 2;
while (null == bit) {
bit = shrinkMethod(aImgBytes, w, h);
_resizeTimes++;
if (_resizeTimes > 5) {
return bit;
}
w = w / 2;
h = h / 2;
}
return bit;
}

private static Bitmap shrinkMethod(byte[] aImgByte, int width, int height) {
Bitmap bit = null;
        BitmapFactory.Options bitopt = new BitmapFactory.Options();
bitopt.inJustDecodeBounds = true;
BitmapFactory.decodeByteArray(aImgByte, 0, aImgByte.length, bitopt);

if (width == 0) {
width = 1;
}
if (height == 0) {
height = 1;
}

int h = (int) Math.ceil(bitopt.outHeight / width);
int w = (int) Math.ceil(bitopt.outWidth / height);

if (h > 1 || w > 1) {
if (h > w) {
bitopt.inSampleSize = h;
} else {
bitopt.inSampleSize = w;
}
}
          bitopt.inJustDecodeBounds = false;
try {
bit = BitmapFactory.decodeByteArray(aImgByte, 0, aImgByte.length,bitopt);
} catch (OutOfMemoryError e) {
bit = null;
}

return bit;
}

public static Bitmap createImg(File aFile) {
BitmapFactory.Options bitopt = new BitmapFactory.Options();
bitopt.inJustDecodeBounds = false;
Bitmap bit = null;
try {
bit = BitmapFactory.decodeFile(aFile.getAbsolutePath(), bitopt);
} catch (OutOfMemoryError e) {
bit = null;
}
if (null == bit) {
bitopt.inJustDecodeBounds = true;
BitmapFactory.decodeFile(aFile.getAbsolutePath(), bitopt);
}
int _resizeTimes = 0;
int w = bitopt.outWidth / 2;
int h = bitopt.outHeight / 2;
while (null == bit) {
bit = shrinkMethod(aFile, w, h);
_resizeTimes++;
if (_resizeTimes > 5) {
return bit;
}
w = w / 2;
h = h / 2;
}

return bit;
}

public static Bitmap shrinkMethod(File aFile, int width, int height) {
Bitmap bit = null;
BitmapFactory.Options bitopt = new BitmapFactory.Options();
bitopt.inJustDecodeBounds = true;
BitmapFactory.decodeFile(aFile.getAbsolutePath(), bitopt);

if (width == 0) {
width = 1;
}

if (height == 0) {
height = 1;
}

int h = (int) Math.ceil(bitopt.outHeight / width);
int w = (int) Math.ceil(bitopt.outWidth / height);

if (h > 1 || w > 1) {
if (h > w) {
bitopt.inSampleSize = h;

} else {
bitopt.inSampleSize = w;
}
}
bitopt.inJustDecodeBounds = false;
try {
bit = BitmapFactory.decodeFile(aFile.getAbsolutePath(), bitopt);
} catch (OutOfMemoryError e) {
bit = null;
}

return bit;
}
小算法-(水仙花字符串) 算法 求大家帮忙啊,小弟算法不行
public class Solution {
	public static int symmetryPoint(String s) {
		if (s.length() % 2 != 0) {
			String leftValue = "";
			String rightValue = "";
			String str = String.valueOf(s.charAt(s.length() / 2));
			String[] split = s.split(str);
			for (int i = split[0].length() - 1; i >= 0; i--)
				leftValue += split[0].charAt(i);
			rightValue = split[1];
			if (leftValue.equals(rightValue))
				return s.indexOf(str);
			else
				return -1;
		} else
			return -1;
	}

	public static void main(String[] args) {
		System.out.println(symmetryPoint("aa21eaxae12aa"));
	}
}
servlet实现登陆验证的过滤器 servlet编程
package hellow;

/*
 * 本程序用来实现登陆验证的过滤器:
 * 首先取得session,然后验证属性是否存在,如果存在,则继续传递请求,否则,转向登陆页面
 * */
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class LoginFilter implements Filter{

	public void init(FilterConfig config) throws ServletException {
	
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain fc) throws IOException, ServletException {
		HttpServletRequest req=(HttpServletRequest)request;
		HttpSession ses=req.getSession();
		if(ses.getAttribute("userid")!=null){
			fc.doFilter(request, response);
		}else{
			request.getRequestDispatcher("login.jsp").forward(request, response);
		}
	}
	public void destroy() {
	}
}
正则表达式基础 java语言
package 正则表达式;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/*
 * 此程序的目的是熟悉正则表达式的使用过程:
 * 首先:使用字符串建立Pattern(模式)
 * 然后:创建Matcher(匹配器)对象,该对象可以与任何对象匹配,多个匹配器可以共享一个模式
 * 一般的调用顺序为:
 * 		Pattern p = Pattern.compile("a*b");
        Matcher m = p.matcher("aaaaab");
        boolean b = m.matches();
   如果只使用一次正则表达式,则如下的调用更加方便:
        boolean b = Pattern.matches("a*b", "aaaaab");
 */

public class Demo01 {
	public static void main(String args[]){
		String exp="(你好)";
		String str="朋友呀!你好,欢迎光临我的空间";
		//将正则表达式用在本程序中
		Pattern p=Pattern.compile(exp);
		//将得到的模式用来创建匹配器
		Matcher m=p.matcher(str);
		//find()方法判断内容是否和模式匹配上
		while(m.find()){
			//group方法返回匹配上的字符串
			System.out.println("匹配上的字符为:"+m.group());
			//返回匹配的开始索引和结束索引
			int start=m.start();
			int end=m.end();
			//替换使用(你好-->hello)
			StringBuffer sb=new StringBuffer();
			sb.append(str.substring(0,start));
			sb.append("hello");
			sb.append(str.substring(end, str.length()));
			System.out.println("替换后的结构为:"+sb);
		}
		
	}
	

}
中文排序注意 java语言, 排序 中文排序要注意的问题
	String[] strs = {"张三(Z)","李四(L)","王五(W)"};
		//定义一个中文排序器
		Comparator c = Collator.getInstance(Locale.CHINA);
		//升序排列
		Arrays.sort(strs,c);

jsp中利用smartupload上传文件
注意事项:
1.将smartupload.jar包存放于WebRoot\WEB-INF\lib和F:\Tomcat 6.0\lib下。
2.将smartupload.jar引进项目:项目名右击—>build path——>external jar
3.在<@ path import="">中引进smart类

<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<%@ page import="com.jspsmart.upload.*"%>//类地址是固定的,不知是为什么?
<html>
  <head>
    <title>My JSP 'smartupload_demo.jsp' starting page</title>
  </head>
  
  <body>
  <%
  SmartUpload smart=new SmartUpload();
  smart.initialize(pageContext);
  smart.upload();
  smart.save("upload");
  %>
    
  </body>
</html>
http IO java i/o 通过Java HTTP连接将网络图片下载到本地
package imageView;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
 * @说明 从网络获取图片到本地
 * @author 崔素强
 * @version 1.0
 * @since
 */
public class GetImage {
	/**
	 * 测试
	 * @param args
	 */
	public static void main(String[] args) {
		String url = "http://www.baidu.com/img/baidu_sylogo1.gif";
		byte[] btImg = getImageFromNetByUrl(url);
		if(null != btImg && btImg.length > 0){
			System.out.println("读取到:" + btImg.length + " 字节");
			String fileName = "百度.gif";
			writeImageToDisk(btImg, fileName);
		}else{
			System.out.println("没有从该连接获得内容");
		}
	}
	/**
	 * 将图片写入到磁盘
	 * @param img 图片数据流
	 * @param fileName 文件保存时的名称
	 */
	public static void writeImageToDisk(byte[] img, String fileName){
		try {
			File file = new File("C:\\" + fileName);
			FileOutputStream fops = new FileOutputStream(file);
			fops.write(img);
			fops.flush();
			fops.close();
			System.out.println("图片已经写入到C盘");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 根据地址获得数据的字节流
	 * @param strUrl 网络连接地址
	 * @return
	 */
	public static byte[] getImageFromNetByUrl(String strUrl){
		try {
			URL url = new URL(strUrl);
			HttpURLConnection conn = (HttpURLConnection)url.openConnection();
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(5 * 1000);
			InputStream inStream = conn.getInputStream();//通过输入流获取图片数据
			byte[] btImg = readInputStream(inStream);//得到图片的二进制数据
			return btImg;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * 从输入流中获取数据
	 * @param inStream 输入流
	 * @return
	 * @throws Exception
	 */
	public static byte[] readInputStream(InputStream inStream) throws Exception{
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while( (len=inStream.read(buffer)) != -1 ){
			outStream.write(buffer, 0, len);
		}
		inStream.close();
		return outStream.toByteArray();
	}
}
scanner的正则功能 java io
package lianshou;
//scanner可以实现去掉空格的作用,实现正则表达式
import java.util.Scanner;
public class Example{
	public static void main(String args[]) throws Exception{
		Scanner sc=new Scanner(System.in);
		int x=sc.nextInt();
		int y=sc.nextInt();
		System.out.print(x+y);//输入2 3
		sc.close();	
	}
};
面向对象之继承2 java实战经典代码
package lianshou;

abstract class A{	// 是定义了一个抽象类
	public A(){
		System.out.println("A、抽象类中的构造方法。") ;
	}
};
class B extends A{	// 继承抽象类,因为B是普通类,所以必须覆写全部抽象方法
	public B(){
		super() ;
		System.out.println("B、子类中的构造方法。") ;
	}
};
public class Example{
	public static void main(String args[]){
		B b = new B() ;
	}
};
面向对象之继承1 java实战经典代码
package lianshou;

import java.io.*;

class person{
	void print(){
		
		System.out.println("person->print()");
	}
	public void fun(){
		System.out.println("person->fun()");
	}
};
class student extends person{
	 public void print(){
		 super.print();
		 System.out.println("student->print()");
	}
}
public class Example{
	public static void main(String args[]) {
		person p=new student();
		p.print();
		p.fun();
	}
}
数据库操作例子 jdbc
package lianshou;

import java.sql.Connection ;
import java.sql.DriverManager ;
import java.sql.Statement ;
import java.sql.ResultSet ;
public class Example{
	// 定义MySQL的数据库驱动程序
	public static final String DBDRIVER = "org.gjt.mm.mysql.Driver" ;
	// 定义MySQL数据库的连接地址
	public static final String DBURL = "jdbc:mysql://localhost:3306/cheng" ;
	// MySQL数据库的连接用户名
	public static final String DBUSER = "root" ;
	// MySQL数据库的连接密码
	public static final String DBPASS = "346520" ;
	public static void main(String args[]) throws Exception {
		Connection conn = null ;		// 数据库连接
		Statement stmt = null ;		// 数据库的操作对象
		ResultSet rs = null ;		// 保存查询结果
		String sql = "SELECT id,age,name,dizhi FROM user" ;
		Class.forName(DBDRIVER) ;	// 加载驱动程序
		conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS) ;
		stmt = conn.createStatement() ;
		rs = stmt.executeQuery(sql) ;
		while(rs.next()){	// 依次取出数据
			int id = rs.getInt("id") ;	// 取出id列的内容
			int age = rs.getInt("age") ;	// 取出age列的内容
			String name = rs.getString("name") ;	// 取出name列的内容
			String dizhi = rs.getString("dizhi") ;	// 取出name列的内容
			
			System.out.print("编号:" + id + ";") ;
			System.out.print("年龄:" + age + ";") ;
			System.out.print("姓名:" + name + ";") ;
			System.out.println("地址:" + dizhi + ";") ;
			System.out.println("-----------------------") ;
		}
		rs.close() ;
		stmt.close() ;
		conn.close() ;			// 数据库关闭
	}
};
将信息以指定的格式存入文件 file Java IO 之字符集相关及文件合并
import java.io.* ;

public class EncodeDemo
{
	public static void main(String args[]) throws Exception
	{
		OutputStream out = null ;
		out = new FileOutputStream(new File("D:/FileTest/a.txt")) ;
		String str = "Hello,World" ;
		out.write(str.getBytes("GB2312")) ;
		out.close() ;
	}
};
将系统属性输出到指定流上 file Java IO 之字符集相关及文件合并
public class ShowPropertiesDemo
{
	public static void main(String args[])
	{
		// 通过此代码观察一下当前JVM中设置的属性
		System.getProperties().list(System.out) ;
	}
}
Servlet 自学Servlet_3_response
		//更改response的码表,通知服务器用UTF-8码表去取response中的数据,然后写给客户机
		response.setCharacterEncoding("UTF-8");  
		//通知浏览器以UTF-8码表打开回送的数据
		//response.setHeader("content-type", "text/html;charset=UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		String data = "中国";
		PrintWriter writer = response.getWriter();
		writer.write(data);
Java中给数字补位 java语言 Java中给数字补位
int number = 1;   
NumberFormat formatter = NumberFormat.getNumberInstance();   
formatter.setMinimumIntegerDigits(4);   
formatter.setGroupingUsed(false);   
String s = formatter.format(number);   
		    
System.out.println(s);
选择排序 排序
package lianshou;
/** 
* 选择排序法
*/ 
import java.util.Calendar; 
public class Example{
	public static void main(String[] args){ 
		int len=10; 
		int[] a=new int[len]; 
		for(int i=0;i<len;i++){ 
			int t=(int)(Math.random()*10+1); //random产生的是小数
			a[i]=t;
		} 
		
        selectSort select=new selectSort(); 
        Calendar cal=Calendar.getInstance(); 
        System.out.println("排序前:"+cal.getTime()); 
        for(int i=0;i<a.length-1;i++){   
            System.out.println(a[i]);   
        }   
        select.sort(a); 
        cal=Calendar.getInstance(); 
        System.out.println("排序后:"+cal.getTime());
        for(int i=0;i<a.length-1;i++){   
            System.out.println(a[i]);   
        }  
    } 
} 
class selectSort {
	public void sort(int a[]){ 
		int position=0;        
		for(int i=0;i<a.length;i++){              
			int j=i+1;          
			position=i;              
            int temp=a[i];              
            for(;j<a.length;j++) {       
            	if(a[j]<temp){        
            		temp=a[j];          
            		position=j;          
            		}         
            	}              
            a[position]=a[i];              
            a[i]=temp;          
           }         
      } 
} 
冒泡排序 排序
package lianshou;
/** 
* 冒泡排序法 
*/ 
import java.util.Calendar; 
public class Example { 
	public static void main(String[] args) {  
    // TODO Auto-generated method stub 
    int len=10; 
    int[] a=new int[len]; 
    for(int i=0;i<len;i++) {
    	int t=(int)(Math.random()*10+1); 
	    a[i]=t;
	    }  
    bubbleSort bub=new bubbleSort(); 
    Calendar cal=Calendar.getInstance(); //计算出排序的时间
    System.out.println("排序前:"+cal.getTime()); 
    for(int i=0;i<a.length-1;i++){
    	System.out.println(a[i]);
    }
    bub.Sort(a); 
    cal=Calendar.getInstance(); 
    System.out.println("排序后:"+cal.getTime()); 
    for(int i=0;i<a.length-1;i++){
    	System.out.println(a[i]);
    }
   } 
} 


class bubbleSort{ 
	public void Sort(int a[]){
		int temp=0;      
        for(int i=0;i<a.length-1;i++){
        	for(int j=0;j<a.length-1-i;j++){ //a.length-1-i到a.length的数据已经排好序了;
        		if(a[j]>a[j+1]){     
        			temp=a[j];              
        			a[j]=a[j+1];              
        			a[j+1]=temp;}
        	}
        }
	}
}
             
      
 
Global site tag (gtag.js) - Google Analytics