มาทำ CAPTCHA ใช้เองดีกว่า 
CAPTCHA คือ ตัวอักษรยึกยือ ไว้กัน bot ใน web site ต่างๆ
ตัวอย่าง captcha จาก http://en.wikipedia.org/wiki/CAPTCHA






ซึ่งเราจะใช้ C# สร้าง Captcha ง่ายๆ แบบของเราเองดังนี้

int count = 0;
Image img;
Random rand = new Random();
for (int ii = 0; ii < 1000; ii++)
{
img = new Bitmap(120, 70);
Graphics g = Graphics.FromImage(img);

int i = rand.Next(10000);
String s = "" + (char)(rand.Next(26) + 65);
s += (char)(rand.Next(26) + 65);
s += i;

g.DrawString(s, new Font("Tahoma", 22, FontStyle.Regular), Brushes.Black, 5, 10);

for (int j = 0; j < 10; j++)
{
int x1, y1, x2, y2;
x1 = rand.Next(26);
x2 = rand.Next(26) + 94;
y1 = rand.Next(70);
y2 = rand.Next(70);

g.DrawLine(new Pen(Color.FromArgb(rand.Next(70), rand.Next(70), rand.Next(70))), x1, y1, x2, y2);

}

g.Flush();
img.Save("D://capcha//" + count + ".PNG", System.Drawing.Imaging.ImageFormat.Png);


String path, key, phone;
// id = Int32.Parse(this.textBox_id.Text);
path = count + ".PNG";
key = s;


string cs = @"server=localhost;userid=root;password=1234;database=yyy";
MySqlConnection conn = new MySqlConnection(cs);

String sql = @"INSERT INTO capcha VALUES (0, '" + path + "','" + key + "' )";
MySqlCommand comm = new MySqlCommand(sql, conn);
conn.Open();
comm.ExecuteNonQuery();


conn.Close();

count++;
}





จะเห็นว่ามีการ เก็บ key ที่ถูกต้องของรูปนั้นๆไว้ใน database ด้วย
ตัวอย่าง captcha ที่ได้จากโปรแกรม


[ view entry ] ( 2335 views )   |  permalink  |  $star_image$star_image$star_image$star_image$star_image ( 3 / 1752 )
การต่อ DATABASE MySQL พร้อม Insert Image 
Insert และ เอา รูป จาก Database มาแสดง
1 create table ดังนี้
CREATE TABLE `customers` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(30) NOT NULL,
`surname` varchar(30) NOT NULL,
`phone` varchar(30) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

สร้างหน้าตาดังนี้






















ด้านซ้ายคือ ImagePanel ซึ่งมี code ดังนี้





import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
public class ImagePanel extends JPanel{
BufferedImage img;
public ImagePanel(){}
public void setImage(BufferedImage i){
img = i;
repaint();
}
public BufferedImage getImage(){
return img;
}
public void paint(Graphics g){
g.drawImage(img, 0, 0,this.getWidth(),this.getHeight(), this);
}
}



code ของหน้าจอหลัก

import java.awt.EventQueue;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.filechooser.FileFilter;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.UIManager;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.sql.*;

public class InsertProduct extends JFrame
{

private JPanel contentPane;
private JTextField txt_name;
private JTextField txt_price;
private ImagePanel imagePanel;

/**
* Launch the application.
*/
public static void main(String[] args)
{
try
{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (Exception e){}
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
InsertProduct frame = new InsertProduct();
frame.setVisible(true);
} catch (Exception e)
{
e.printStackTrace();
}
}
});
}
public InsertProduct()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);

imagePanel = new ImagePanel();
imagePanel.setBounds(10, 11, 248, 240);
contentPane.add(imagePanel);

JButton btnBrowse = new JButton("browse image");
btnBrowse.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
JFileChooser fc = new JFileChooser("c://");
fc.setFileFilter(new JPEGImageFileFilter());
int res = fc.showOpenDialog(null);
if (res == JFileChooser.APPROVE_OPTION)
{
File file = fc.getSelectedFile();
// this.
try
{
imagePanel.setImage(ImageIO.read(file));
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
btnBrowse.setBounds(268, 11, 156, 23);
contentPane.add(btnBrowse);

JLabel lblProductName = new JLabel("product name");
lblProductName.setBounds(268, 51, 102, 14);
contentPane.add(lblProductName);

txt_name = new JTextField();
txt_name.setBounds(268, 74, 156, 23);
contentPane.add(txt_name);
txt_name.setColumns(10);

JLabel lblPricePerUnit = new JLabel("price per unit");
lblPricePerUnit.setBounds(268, 108, 102, 14);
contentPane.add(lblPricePerUnit);

txt_price = new JTextField();
txt_price.setColumns(10);
txt_price.setBounds(268, 131, 156, 23);
contentPane.add(txt_price);

JButton btn_insert = new JButton("Insert");
btn_insert.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
Connection con = null;
Class.forName("com.mysql.jdbc.Driver");
con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/yyy", "root", "1234");

Class.forName("com.mysql.jdbc.Driver");

String price = txt_price.getText();
String name = txt_name.getText();

String insert = "INSERT INTO product(id,name,price_per_unit,image) " + " VALUES (0,?,?,?)";

PreparedStatement preparedStmt = con.prepareStatement(insert);
ByteArrayOutputStream buff = new ByteArrayOutputStream();
ImageIO.write(imagePanel.getImage(), "PNG", buff);
byte[] buff_temp = buff.toByteArray();
ByteArrayInputStream inBuff = new ByteArrayInputStream(buff_temp);

preparedStmt.setString(1, name);
preparedStmt.setString(2, price);
preparedStmt.setBinaryStream(3, inBuff, buff_temp.length);

preparedStmt.execute();
System.out.println("finish");
con.close();
} catch (Exception ee)
{
ee.printStackTrace();
}
}
});
btn_insert.setBounds(269, 185, 89, 23);
contentPane.add(btn_insert);
}
}
class JPEGImageFileFilter extends FileFilter implements java.io.FileFilter{
public boolean accept(File f){
if (f.getName().toLowerCase().endsWith(".jpeg"))
return true;
if (f.getName().toLowerCase().endsWith(".jpg"))
return true;
if (f.isDirectory())
return true;
return false;
}
public String getDescription()
{
return "JPEG files";
}
}




จะเห็นว่า ตอนInsert จะใช้ PreparedStatement มาช่วย
ByteArrayOutputStream buff = new ByteArrayOutputStream();
ImageIO.write(imagePanel.getImage(), "PNG", buff);
byte[] buff_temp = buff.toByteArray();
ByteArrayInputStream inBuff = new ByteArrayInputStream(buff_temp);

ส่วนนี้ใช้ Save Image ลง Memory ก่อน แล้วค่อย Save ลง DATABASE อีกทีหนึ่ง


ดึงข้อมูลพ้อมรูปมาแสดง




import java.awt.image.BufferedImage;
import javax.swing.JPanel;
import javax.swing.JLabel;
public class ProductPanel extends JPanel
{
public ProductPanel()
{
setLayout(null);
imagePanel = new ImagePanel();
imagePanel.setBounds(0, 0, 223, 109);
add(imagePanel);
label_id = new JLabel("New label");
label_id.setBounds(322, 9, 118, 26);
add(label_id);
label_name = new JLabel("New label");
label_name.setBounds(322, 46, 118, 26);
add(label_name);
label_price = new JLabel("New label");
label_price.setBounds(322, 83, 118, 26);
add(label_price);
lblUd = new JLabel("id");
lblUd.setBounds(233, 9, 62, 26);
add(lblUd);
lblName = new JLabel("name");
lblName.setBounds(233, 46, 62, 26);
add(lblName);
lblPricePerUnit = new JLabel("price per unit");
lblPricePerUnit.setBounds(233, 83, 79, 26);
add(lblPricePerUnit);
}

public void setParam(int id, String name, double price, BufferedImage img)
{
this.id=id;
this.name= name;
this.price=price;
this.img=img;

label_id.setText(""+ this.id);
label_name.setText(""+ this.name);
label_price.setText(""+ this.price);

imagePanel.setImage(img);
}

public int id;
public String name;
public double price;
public BufferedImage img;

private JLabel label_price;
private JLabel label_name;
private JLabel label_id;
private ImagePanel imagePanel;
private JLabel lblUd;
private JLabel lblName;
private JLabel lblPricePerUnit;

}




import java.awt.EventQueue;
import java.awt.image.BufferedImage;
import java.sql.*;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;


public class selectProduct extends JFrame
{

private JPanel contentPane;

public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
selectProduct frame = new selectProduct();
frame.setVisible(true);
} catch (Exception e)
{
e.printStackTrace();
}
}
});
}

public selectProduct()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
// //////////////////////////////////
try
{
Connection con = null;
Class.forName("com.mysql.jdbc.Driver");
con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/yyy", "root", "1234");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM product");
Class.forName("com.mysql.jdbc.Driver");

int i=0;
while (rs.next())
{
ProductPanel pp = new ProductPanel();
BufferedImage img = ImageIO.read(rs.getBinaryStream(4));
pp.setParam(rs.getInt(1), rs.getString(2), rs.getDouble(3), img);
pp.setBounds(0, i*120 + 20, 500, 120);
this.contentPane.add(pp);

System.out.println(pp.id +" "+ pp.name);
i++;
}

} catch (Exception ee)
{
ee.printStackTrace();
}

}
}



อาจต้องมีการ set ค่าในดรสำ my.ini สำหรับ ขนาดของ รูป
max_allowed_packet=500M

[ view entry ] ( 2533 views )   |  permalink  |  $star_image$star_image$star_image$star_image$star_image ( 2.9 / 1486 )
ดึง RSS โดยใช้ JAVA 

ดึง RSS โดยใช้ JAVA




try
{
URL yahoo = new URL("http://rss.cnn.com/rss/edition.rss");
BufferedReader in = new BufferedReader(new InputStreamReader(yahoo.openStream()));
Scanner sc = new Scanner(in);

while (sc.hasNext())
{
String s = sc.nextLine();
System.out.println(s);
}

sc.close();

} catch (MalformedURLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}


ในอันนี้จะเป็นการดึง RSS โดยใช้ JAVA ครับ




[ view entry ] ( 17529 views )   |  permalink  |  $star_image$star_image$star_image$star_image$star_image ( 3 / 2281 )
วาดรูปต้นไม้ Binary Search Tree 

เป็นการวาดรูปต้นไม้ binary search tree ครับ






class Tree node

import java.awt.Color;
import java.awt.Graphics;

public class TreeNode {
public int data;
public TreeNode left, right;

public TreeNode() {
}

public TreeNode(int x) {
data = x;
}

public void draw(Graphics g, int x, int y) {


g.setColor(Color.pink);
g.fillOval(x, y, 40, 40);
g.setColor(Color.black);
g.drawString("" + data, x + 15, y + 23);

}
}




class BSTree

import java.awt.Graphics;

public class BSTree {
public TreeNode root;

public void add(int x) {
if (root == null) {
root = new TreeNode(x);
return;
}
add(x, root);
}

public void add(int x, TreeNode n) {
if (n == null)
return;
if (n.data == x)
return;

if (n.data < x) {
if (n.right == null) {
n.right = new TreeNode(x);
} else {
add(x, n.right);
}
} else {
if (n.left == null) {
n.left = new TreeNode(x);
} else {
add(x, n.left);
}
}
}

public int numNode(TreeNode n) {
if (n == null)
return 0;
int k = 0;
if (n.left != null) {
k = k + numNode(n.left);
}
if (n.right != null) {
k = k + numNode(n.right);
}

return k + 1;
}

public int height(TreeNode n) {
if (n == null)
return -1;
if (n.left == null && n.right == null) {
return 0;
}
int kl = 0;
int kr = 0;

if (n.left != null) {
kl = height(n.left);
}
if (n.right != null) {
kr = height(n.right);
}

return kl > kr ? kl + 1 : kr + 1;
}

int stepX;
int stepY;

public void draw(Graphics g, int width, int height) {

int num = numNode(root);
int h = height(root);

stepX = width / (num + 1);
stepY = height / (h + 1);

draw(g, 1, num, 1, root,-1,-1);
}

public int draw(Graphics g, int start_x, int end_x, int height, TreeNode t,int x_mom ,int y_mom) {
int num_l = numNode(t.left);

int x_now=(num_l + start_x) * stepX;
int y_now= height * stepY;



t.draw(g, x_now, y_now);

if (t.left != null) {
draw(g, start_x, start_x + num_l - 1, height + 1, t.left,x_now, y_now);
}
if (t.right!= null) {
draw(g, start_x + num_l + 1, end_x, height + 1, t.right,x_now, y_now);
}

if(x_mom != -1 && y_mom !=-1)
{
g.drawLine(x_mom+15, y_mom+15, x_now+15, y_now+15);
}
return 0;
}

}



call GUI

import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class GUI extends JPanel {
BSTree t;
public GUI() {
t = new BSTree();
for (int i = 0; i < 100; i++) {
int k=(int) (Math.random() * 100);
t.add(k);
System.out.println(k);
}
System.out.println(t.height(t.root));

JFrame f = new JFrame();
f.add(this);
f.setSize(600, 600);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);

}

public void paint(Graphics g) {
super.paint(g);
if(t!=null){
t.draw(g, this.getWidth(), this.getHeight());
}
}

public static void main(String[] args) {

new GUI();
}

}




** ดัดแปลงจากในหนังสือของอาจารย์สมชาย โครงสร้างข้อมูล : ฉบับวาจาจาวา (สมชาย ประสิทธิ์จูตระกูล)**



[ view entry ] ( 20951 views )   |  permalink  |  $star_image$star_image$star_image$star_image$star_image ( 3 / 2463 )
เกม Pong คล้ายๆของ Steve Jobs โดย VB.net ครับ  

ยังไม่เสร็จสมบูรณ์เป็นโจทย์ให้นร.ไปทำต่อนะครับ






Public Class Form1
Dim a(5, 5) As Double
Dim colors(5, 5) As Color
Dim rand As Random = New Random
Dim ballsize As Integer = 20
Dim x, y, vx, vy As Integer


Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

For i = 0 To a.GetUpperBound(0)

For j = 0 To a.GetUpperBound(0)
a(i, j) = 1
colors(i, j) = Color.FromArgb(rand.Next(255), rand.Next(255), rand.Next(255))
Next
Next
Me.DoubleBuffered = True

x = 300
y = 300
vx = rand.NextDouble * 20 - 10
vy = rand.NextDouble * 20 - 10

Timer1.Start()
Timer1.Interval = 10
End Sub



Private Sub Form1_Paint(sender As Object, e As PaintEventArgs) Handles MyBase.Paint
Dim w, h As Integer
w = Me.Width
h = 80

For i = 0 To a.GetUpperBound(0)

For j = 0 To a.GetUpperBound(0)
If a(i, j) = 1 Then
e.Graphics.FillRectangle(New SolidBrush(colors(i, j)), _
CInt(j * w / a.GetLength(1)), _
CInt(i * h / a.GetLength(0)), _
CInt(w / a.GetLength(1)), _
CInt(h / a.GetLength(0)))
End If
Next
Next

e.Graphics.FillEllipse(New SolidBrush(Color.Red), _
CInt(x - ballsize), _
CInt(y - ballsize), _
CInt(ballsize * 2), _
CInt(ballsize * 2))

End Sub
Private Sub Form1_SizeChanged(sender As Object, e As EventArgs) Handles MyBase.SizeChanged
Refresh()
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Dim w, h As Integer
w = Me.Width
h = 80
x = x + vx
y = y + vy
If x + ballsize > Me.Width Then
x = Me.Width - ballsize
vx = vx * -1
End If

If y + ballsize > Me.Height Then
y = Me.Height - ballsize
vy = vy * -1
End If
If x - ballsize < 0 Then
x = 0 + ballsize
vx = vx * -1
End If

If y - ballsize < 0 Then
y = 0 + ballsize
vy = vy * -1
End If

For i = 0 To a.GetUpperBound(0)

For j = 0 To a.GetUpperBound(0)
If a(i, j) = 1 Then
If x - ballsize < j * w / a.GetLength(1) + w / a.GetLength(1) And _
x - ballsize > j * w / a.GetLength(1) And _
y - ballsize < i * h / a.GetLength(0) + h / a.GetLength(0) And _
y - ballsize > i * h / a.GetLength(0) _
Then
a(i, j) = 0
vy = vy * -1
End If
End If
Next
Next
Refresh()
End Sub
End Class



[ view entry ] ( 2524 views )   |  permalink  |  $star_image$star_image$star_image$star_image$star_image ( 3 / 2213 )

<<First <Back | 1 | 2 | 3 | 4 | 5 | Next> Last>>